如何找到匹配模式的行并删除它们?

在一个有很多行的文件中,我想删除以HERE IT IS开头的行。

如何仅使用命令行工具执行此操作?

试试sed

 sed -i '/^HERE IT IS/d'  

警告:使用sed -i开关时最好进行备份:

 sed -i.bak '/^HERE IT IS/d'  

原始文件将保留为.bak ,修改后的文件将为

除了你收到的非常好的grepsed答案之外,还有一些其他工具可以做同样的事情:

  • 一些Perl方式:

     perl -ne '/^HERE IT IS/ || print' file > newfile perl -ne 'print if !/^HERE IT IS/' file > newfile perl -ne 'print unless /^HERE IT IS/' file > newfile 

    您可以将-i开关添加到任何示例以编辑文件:

     perl -i.bak -ne '/^HERE IT IS/ || print' file 
  • (克)AWK

     awk '!/^HERE IT IS/' file > newfile 

    GNU awk较新版本(4.1.1及更高版本)(Linux上的默认awk )也可以编辑文件:

     gawk -i inplace '!/^HERE IT IS/' file 
  • Shell( bashzshksh ,可能是其他人)。 这有点傻,但可以做到,但其他工具更好。

     while IFS= read -r line; do [[ $line =~ ^"HERE IT IS" ]] || printf "%s\n" "$line" done < file > newfile 

我会用grep来过滤掉它们。 例如 :

 grep -v "^HERE IT IS" infile > outfile 

然后将outfile移回infile。

sed绝对是要走的路。

对命令@heemayl稍作修改后,您将删除该行,无论模式中是否使用相同的大小写,由于模式引用中的I。

 sed -i '/HERE IT IS/Id'  

如果您希望在目录中有多个文件,则可以将它与find结合使用。

 find . -maxdepth 1 -type f -exec sed -i.bak '/HERE IT IS/Id' {} + 

maxdepth选项意味着它不会递归到目录中。

另一个python选项:

 #!/usr/bin/env python3 [print(l, end = "") for l in open(f).readlines() if not l.startswith("HERE IT IS")] 

其中f是文件的路径,在引号之间。

grep的

 grep -P '^(?!HERE IT IS)' file 

(?!HERE IT IS)负前瞻断言,它使正则表达式引擎匹配所有行起始边界( 通常与^匹配 ),只有当它后面没有字符串时才会出现这个问题。

python

 #!/usr/bin/python3 import sys fil = sys.argv[1] with open(fil) as f: for line in f: if not line.startswith('HERE IT IS'): print(line, end="") 

将脚本保存在一个文件中,比如说script.py然后通过终端上面的命令运行它。

 python3 script.py infile 

您可以在Ex模式下使用Vim:

 ex -sc 'g/^HERE IT IS/d' -cx file 
  1. 全球搜索

  2. d删除

  3. x保存并关闭