简体   繁体   English

删除shell中一行的最后一个单词

[英]Delete the last word of a line in shell

I'm looking for how to delete the last word of a line in shell ! 我正在寻找如何删除shell中一行的最后一个单词! I use sed but I only found the way how delete the lase word of every line, but not a specify line. 我使用sed但我只找到了如何删除每一行的激光词,而不是指定行。 For exemple: I have a file test.db 例如:我有一个文件test.db

key1 value1
key2 value2
key3 value3

And I just want to delete value3 我只想删除value3

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

This line just delete the last word of every line ! 这一行只删除每一行的最后一个字!

试试这个 :

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

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 : 如果要删除key3行中的最后一个单词:

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

Here is an awk to remove last field: 这是删除最后一个字段的awk

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

Deleting the last word of your line 删除行的最后一个单词

since you are targeting the line key3 value3 因为你的目标是key3 value3

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

where \\S is represents a digit that is not a space or whitespace. 其中\\ S表示不是空格或空格的数字。

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 线条图案表示在您要定位的线条上找到的图案

This might work for you (GNU sed): 这可能适合你(GNU sed):

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

this removes the last non-space token from the last line (keeping any surrounding white space). 这将从最后一行中删除最后一个非空格标记(保留任何周围的空白区域)。

To remove surrounding white space as well use: 要删除周围的空白区域,请使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM