Delete last word of string in shell

I am looking for how to remove the last word of a string in a shell! I use sed, but I found a way to remove the lase word for each line, but not specify a line. For example: I have a test.db file

key1 value1 key2 value2 key3 value3 

And I just want to remove the value3

 sed -is/'\w*$'// test.db 

This line simply removes the last word of each line!

+5
source share
5 answers

If you want to remove the last word only from the last line, you can use:

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

If you want to remove the last word from the string for key3 :

 sed -i '/key3/s/\w*$//' test.db 
+2
source

Try the following:

 sed -i '1{s/[^ ]\+\s*$//}' file test.db 
+2
source

Here is awk to remove the last field:

 echo "one two three" | awk '{$NF="";sub(/[ \t]+$/,"")}1' one two 
+2
source

Delete the last word of your line

as you aim the string key3 value3

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

where \ S is a number that is not a space or a space.

Deleting the last word of a specific line (general rule)

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

a line pattern is a pattern that is in the line that you want to target

+1
source

This may work for you (GNU sed):

 sed -r '$s/(\s*)\S+(\s*)$/\1\2/' file 

this removes the last non-spatial token from the last line (preserving any surrounding empty space).

To remove the surrounding white space, use:

 sed -r '$s/\s*\S+\s*$//' file 
0
source

Source: https://habr.com/ru/post/1210432/


All Articles