bash 删除文件中包含特定字符的所有行

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

Delete all the lines in a file that contains a specific character

perlbashunixcommand-lineawk

提问by discipulus

I want to delete all the rows/lines in a file that has a specific character, '?' in my case. I hope there is a single line command in Bash or AWK or Perl. Thanks

我想删除具有特定字符“?”的文件中的所有行/行 就我而言。我希望在 Bash、AWK 或 Perl 中有一个单行命令。谢谢

采纳答案by jm666

Here are already grep, sed and perl solutions - only for fun, pure bash one:

这里已经有 grep、sed 和 perl 解决方案 - 仅用于有趣的纯 bash 解决方案:

pattern='?'
while read line
do
    [[ "$line" =~ "$pattern" ]] || echo "$line"
done

translated

翻译

  • for every line on the STDIN
  • match it for the pattern =~
  • and if the match is not successful ||- print out the line
  • 对于 STDIN 上的每一行
  • 匹配它的模式 =~
  • 如果匹配不成功||- 打印出该行

回答by dogbane

You can use sedto modify the file "in-place":

您可以使用sed“就地”修改文件:

sed -i "/?/d" file

Alternatively, use grep:

或者,使用 grep:

grep -v "?" file > newfile.txt

回答by Fredrik Pihl

Even better, just a single line using sed

更好的是,只需一行使用 sed

sed '/?/d' input

use -ito edit file in place.

用于-i就地编辑文件。

回答by ysth

perl -i -ne'/\?/ or print' file

or

或者

perl -i -pe's/^.*?\?.*//s' file

回答by Vijay

awk '!(##代码##~/?/){print ##代码##}' file_name