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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27790078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:07:36  来源:igfitidea点击:

Delete the last word of a line in shell

linuxbashshellsedsh

提问by 03t02

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

我正在寻找如何删除 shell 中一行的最后一个单词!我使用 sed 但我只找到了如何删除每一行的 lase 字的方法,而不是指定的行。例如:我有一个文件 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 !

这一行只是删除每一行的最后一个字!

采纳答案by lurker

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:

如果您想从 for 行中删除最后一个单词key3

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

回答by Gilles Quenot

Try this :

尝试这个 :

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

回答by Jotne

Here is an awkto remove last field:

这是awk删除最后一个字段:

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

回答by repzero

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

线条图案表示在您要定位的线条上找到的图案

回答by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

sed -r '$s/(\s*)\S+(\s*)$//' 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