bash “sed”命令删除与第一个单词上的确切字符串匹配的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33419362/
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
"sed" command to remove a line that match an exact string on first word
提问by Dani Polo
I'm working in a small bash script. I need to remove an entire line that match an exact word in only the first word of the line.
我正在使用一个小的 bash 脚本。我需要删除仅在该行的第一个单词中与精确单词匹配的整行。
That's how the text file looks:
这就是文本文件的样子:
John is a dumb
Maria is awesome
Toni and Maria are funny
I want to remove the just the second line.
我想删除第二行。
Right now, I can match the exact word "maria" but it removes the third line too:
现在,我可以匹配确切的单词“maria”,但它也删除了第三行:
sed -i "/\b\(maria\)\b/d" file.txt
How to specify just the first word?
如何仅指定第一个单词?
Thanks!
谢谢!
回答by miken32
Currently you are looking for "maria" surrounded by a word boundary (represented by \b
.) Instead look for "maria" preceded by the start of line (represented by ^
.) Note I've also removed unnecessary parentheses and added the /I
flag, which will make the search case-insensitive. Your original wouldn't have matched "Maria".
目前您正在寻找“玛丽亚”,由一个单词边界包围(表示为\b
。)相反寻找“玛丽亚”,由行的开始之前(以表示^
)。注意我还删除不必要的括号内添加的/I
标志,这将使搜索不区分大小写。您的原件不会与“玛丽亚”匹配。
sed -i "/^maria\b/Id" file.txt
Edit: fixed case insensitive flag to I instead of i!
编辑:将不区分大小写的标志固定为 I 而不是 i!