linux 删除grep行_如何在Linux中使用grep来Grep 2行?

linux 删除grep行

grep is excellent to match patterns from STDOUT/text files in command line or scripts. It’s handy. Sometimes, our problem is more complex than finding a keyword from a file. On a first thought, it may sound impossible using grep for such complex problems. But grep can be quite powerful than we thought. Today, let’s check one example.

grep非常适合在命令行或脚本中匹配STDOUT /文本文件中的模式。 方便 有时,我们的问题比从文件中找到关键字更复杂。 乍一想,使用grep解决如此复杂的问题似乎是不可能的。 但是grep可能比我们想象的强大。 今天,让我们来看一个例子。

grep的问题 (The problem to grep)

The problem is as follows. We want to check whether the ~/.bashrc file contains 2 consecutive lines (okay to assume they are not at the beginning of the file):

问题如下。 我们要检查~/.bashrc文件是否包含2个连续的行(可以假设它们不在文件的开头):

export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$PATH

There are 2 criteria: 1. these 2 lines must both exist, and 2. these 2 lines are consecutive.

有两个条件:1.这两条线必须都存在,并且2.这两条线是连续的。

grep的困难 (The difficulties with grep)

Right, the basic pattern format by grep has difficulties to understand the \n (new line) as the input is matched line by line. But we don’t need to stop here. grep has many options. The key is to make it match \n. First, we need to make grep not use \n as the line separator. Second, we need to make grep treat \n as a normal character.

正确,由于输入逐行匹配,因此grep的基本模式格式难以理解\n (换行)。 但是我们不必在这里停下来。 grep有很多选择 。 关键是使其匹配\n 。 首先,我们需要使grep不要使用\n作为行分隔符。 其次,我们需要使grep\n视为正常字符。

解决方案 (The solution)

For the first purpose, the -z option is useful. It makes grep "treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.". For the second purpose, the -P option is useful. It makes grep use Perl-compatible regular expression (PCRE) grammar which can treat \n as a normal character.

首先, -z选项很有用。 它使grep “将输入和输出数据作为行序列进行处理,每行以零字节( ASCII NUL字符)而不是换行符结尾”。 对于第二个目的, -P选项很有用。 它使grep使用与Perl兼容的正则表达式(PCRE)语法,该语法可以将\n视为正常字符。

With all these analysis, we can build the command now:

通过所有这些分析,我们现在可以构建命令:

grep -Pzl '\nexport GOPATH=\$HOME/go\nexport PATH=\$GOPATH/bin:\$PATH\n' \
~/.bashrc

The first \n make sure the first line start after a \n. The last \n makes sure the second line is in a single line instead of a head of a longer line. \$ is used because $ in PCRE is a special character.

第一\n确保第一行 \n之后开始 。 最后一个\n确保第二行位于一行中,而不是较长行的开头。 \$是因为PCRE中的$是特殊字符。

The same technique can be used for perl one-liners too: How to Match Multiple Lines using Regex in Perl One-liners.

相同的技术也可以用于perl单线: 如何在Perl单线中使用Regex匹配多行

翻译自: https://www.systutorials.com/how-to-grep-2-lines-using-grep-in-linux/

linux 删除grep行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值