好
我知道这是一个微不足道的问题,但是:如何从两个已知模式/单词之间的文件中删除行:
pattern1
垃圾
模式2
获得:
pattern1
pattern2
有没有人知道用于研究sed的好(简单的书面!)资源?有很多明显的例子吗?
Pau*_*ce. 14
sed -n '/pattern1/{p; :a; N; /pattern2/!ba; s/.*\n//}; p' inputfile
Run Code Online (Sandbox Code Playgroud)
说明:
/pattern1/{ # if pattern1 is found
p # print it
:a # loop
N # and accumulate lines
/pattern2/!ba # until pattern2 is found
s/.*\n// # delete the part before pattern2
}
p # print the line (it's either pattern2 or it's outside the block)
Run Code Online (Sandbox Code Playgroud)
编辑:
有些版本sed需要用勺子喂食:
sed -n -e '/pattern1/{' -e 'p' -e ':a' -e 'N' -e '/pattern2/!ba' -e 's/.*\n//' -e '}' -e 'p' inputfile
Run Code Online (Sandbox Code Playgroud)
这可能对你有用:
sed '/pattern1/,/pattern2/{//!d}' file
Run Code Online (Sandbox Code Playgroud)
这很容易用 awk 完成:
BEGIN { doPrint = 1; }
/pattern1/ { doPrint = 0; print $0; }
/pattern2/ { doPrint = 1; }
{ if (doPrint) print $0; }
Run Code Online (Sandbox Code Playgroud)
我发现sed 信息相当容易阅读,有很多例子。对于同样的事情AWK。