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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10219438/
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 02:04:28  来源:igfitidea点击:

Delete last word in each line in bash

regexbashsed

提问by Michael Rauh

I am trying to go through a file, and delete the last word in each line. Currently, I am using the command

我正在尝试浏览一个文件,并删除每一行中的最后一个单词。目前,我正在使用命令

sed 's/^*\n//' old.txt > new.txt

but it is coming out that old.txt is the same as new.txt. Thanks for any help, and let me know if I can clarify the question. Also, in order to define 'word' I am just using spaces.

但结果是 old.txt 与 new.txt 相同。感谢您的帮助,如果我能澄清问题,请告诉我。另外,为了定义“单词”,我只是使用空格。

回答by David Z.

Try the following. \w*matches the last word inside of the file and $anchors the search to the end of the line.

请尝试以下操作。\w*匹配文件中的最后一个单词$并将搜索定位到行尾。

sed s/'\w*$'// old.txt > new.txt

The reason that old.txt is coming out as new.txt is likely because your regular expression ^*\nis not matching any lines in old.txt.

old.txt 作为 new.txt 出现的原因可能是因为您的正则表达式^*\n与 old.txt 中的任何行都不匹配。

回答by E1Suave

The following is an inline edit. PRIOR TO RUNNING ANYTHING PLEASE BACKUP YOUR FILE.

以下是内联编辑。在运行任何东西之前,请备份您的文件。

sed -i 's/[[:alnum:]]*$//' /yourfile

If you are working on OS X, you may want to try the following

如果您在 OS X 上工作,您可能想尝试以下操作

sed -i '' 's/[[:alnum:]]*$//' /yourfile

If you are not interested in writing directly back to the original file, but would like the output to be printed.

如果您对直接写回原始文件不感兴趣,但希望打印输出。

sed 's/[[:alnum:]]*$//' /yourfile