Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I am trying to find out how to remove the last word in a file.
For example, a line in a file will contain:
one two three fourAnd I want to remove the word "four" from the line.
Thanks!

Nails,
Can you please explain what sed does? I'm just unfamiliar with that command. Is there another way using ksh commands?

sed stands for Stream EDitor. It's a common utility used to edit text files from the command line or a script. This particular example prints all lines, but the last. On the last line it uses a regular expression to print everything, but the last field.
What is your definition of 'ksh commands?' You can't use any external commands. There is a way, but first I need the total number of lines in the file. I'd normally use:
flen=$(wc -l < data.file)
but this loop works:
flen=0
while read line
do
((flen+=1))
done < data.fileNow, use this loop:
cnt=0
while read line
do
((cnt+=1))
if [[ $cnt -eq $flen ]]
then # last line
# set the separate fields as command line arguments
set - $(echo "$line")
cnt2=1
while [[ $cnt2 < $# ]]
do
argchar=$(eval echo \$$cnt2)
printf "%s " $argchar
((cnt2+=1))
done
else
echo "$line"
fi
done < data.file
echo
# end scriptIn the above script, print everything, but the last line. On the last line set each field equal to the command line arguments $1, $2, etc.
The above script works as long as the last line doesn't have over 9 fields. If it does have over 9 fields, the solution is a little more drawn out.

here's one that is more readable: in python though
>>> o = open("output.txt","a")
>>> yourfile = os.path.join("/home","file.txt")
>>> for lines in open(yourfile):
.......# get all words except the last word
.......line = lines.split()[:-1]
.......o.write(' '.join(line) + "\n")
...
>>> o.close()
>>>

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |