SpH*_*SpH 6 unix grep sed pattern-matching
我需要删除一个匹配的行和前一个.例如,在下面的文件中,我需要删除第1行和第2行.
我试过"grep -v -B 1"页面.的."1.txt和我预计它不会打印匹配的行和上下文.
我尝试了如何使用sed删除匹配的行,上面的行和它下面的行?但无法理解sed的用法.
---1.txt--
**document 1** -> 1
**page 1 of 2** -> 2
testoing
testing
super crap blah
**document 1**
**page 2 of 2**
Run Code Online (Sandbox Code Playgroud)
Has*_*kun 12
你想做一些与给出答案非常相似的事情
sed -n '
/page . of ./ { #when pattern matches
n #read the next line into the pattern space
x #exchange the pattern and hold space
d #skip the current contents of the pattern space (previous line)
}
x #for each line, exchange the pattern and hold space
1d #skip the first line
p #and print the contents of pattern space (previous line)
$ { #on the last line
x #exchange pattern and hold, pattern now contains last line read
p #and print that
}'
Run Code Online (Sandbox Code Playgroud)
并作为一条线
sed -n '/page . of ./{n;x;d;};x;1d;p;${x;p;}' 1.txt
Run Code Online (Sandbox Code Playgroud)
对 sed 不太熟悉,但这里有一个 perl 表达式可以做到这一点:
cat FILE | perl -e '@a = <STDIN>;
for( $i=0 ; $i <= $#a ; $i++ ) {
if($i > 0 && $a[$i] =~ /xxxx/) {
$a[$i] = "";
$a[$i-1] = "";
}
} print @a;'
Run Code Online (Sandbox Code Playgroud)
编辑:
其中“xxxx”是您要匹配的内容。