Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete the last word of a line in shell

I'm looking for how to delete the last word of a line in shell ! I use sed but I only found the way how delete the lase word of every line, but not a specify line. For exemple: I have a file test.db

key1 value1
key2 value2
key3 value3

And I just want to delete value3

sed -i s/'\w*$'// test.db

This line just delete the last word of every line !

like image 905
03t02 Avatar asked Jan 06 '15 00:01

03t02


People also ask

How do I remove the last word from a string in shell script?

To remove the last n characters of a string, we can use the parameter expansion syntax ${str::-n} in the Bash shell. -n is the number of characters we need to remove from the end of a string.


Video Answer


4 Answers

If you want to delete the last word only off of the last line, then you can use:

sed -i '$s/\w*$//' test.db

If you want to delete the last word from the line for key3:

sed -i '/key3/s/\w*$//' test.db
like image 158
lurker Avatar answered Oct 23 '22 08:10

lurker


Try this :

sed -i '1{s/[^ ]\+\s*$//}' file test.db
like image 31
Gilles Quenot Avatar answered Oct 23 '22 09:10

Gilles Quenot


Here is an awk to remove last field:

echo "one two three" | awk '{$NF="";sub(/[ \t]+$/,"")}1'
one two
like image 2
Jotne Avatar answered Oct 23 '22 09:10

Jotne


Deleting the last word of your line

since you are targeting the line key3 value3

  sed -i '/key3 value3/s/\S*$//' test.db

where \S is represents a digit that is not a space or whitespace.

Deleting the last word of a particular line (General rule)

   sed -i '/line pattern/s/\S*$//' test.db

line pattern represents a pattern that is found on the line that you want to target

like image 1
repzero Avatar answered Oct 23 '22 07:10

repzero