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行