use*_*939 3 grep sed awk text-processing
例如,假设我想在此文本中查找所有带有“匹配”的行和之前未缩进的行。
Container 1
some text
some text
matching text
some text
Container 2
some text
some text
Container 3
some text
matching text
Run Code Online (Sandbox Code Playgroud)
我想要的结果看起来像这样
Container 1
matching text
Container 3
matching text
Run Code Online (Sandbox Code Playgroud)
这可能吗?
这是一种方法sed:
sed -n '/^[^[:blank:]]/b do # if line is not indented go to label do
//!{ # if line is indented and if it
/matching/H # matches, append it to hold space
}
$b do # if on last line go to label do
b # branch to end of script
: do # label do
x # exchange hold buffer w. pattern space
/\n.*matching/p # if current pattern space matches, print
' infile
Run Code Online (Sandbox Code Playgroud)
如果您还想打印匹配的非缩进行,例如,Container matching stuff即使后面的缩进块中没有任何行匹配,那么只需将最后一个条件更改/matching/p为以消除\n.*限制并打印模式空间,即使它成立只有一行(非缩进)匹配:
sed -n '/^[^[:blank:]]/b do
//!{
/matching/H
}
$b do
b
: do
x
/matching/p
' infile
Run Code Online (Sandbox Code Playgroud)