awk 在匹配之前但在空行之后删除

awk remove before match but after empty line

没有找到完全相似的问题,所以我想问一下:

我有一个文件 gist :

...
must_be_intact

bad_line
bad_line
bad_line
match_line
...

我使用 awk 删除比赛前但比赛后的所有内容 space:

'NR==FNR{if (/match_line/) { 
    i=0;
    while(1) {
        if (NR-i==/^\s*$/) break; 
        del[NR-i]; 
        i=i-1; 
        next
        }
    }
} !(FNR in del)'

但这不能正常工作。帮助改进此代码,或者您可以建议其他方法。

你把它复杂化了。

您可以只使用 tac + awk + tac 操作:

tac file | awk '/^match_line$/,!NF{next} 1' | tac
must_be_intact

must_be_intact
must_be_intact
must_be_intact

must_be_intact
must_be_intact
must_be_intact

must_be_intact

must_be_intact

must_be_intact
must_be_intact

must_be_intact
must_be_intact
must_be_intact

awk 使用范围从 NF==0(表示空行)到只有 match_line 的行,并在操作块中使用 next 跳过该部分.

仅使用您展示的示例,请尝试遵循 awk 代码,用 GNU awk 编写和测试。简单的解释是,将 RS(记录分隔符)设置为在 match_line 之前和主程序中出现 1 次或多次换行;用 NULL 替换第一行,然后按照 RS.

打印这些行
awk -v RS='\n+.*match_line' '{sub(/\n/,"")}1' Input_file
$ sed '/^$/,/match_line/{/match_line/!d}' txt
...
must_be_intact
match_line
...

或者

awk -v m="match_line" '{ if([=11=] ~ /^$/) { while([=11=] != m) getline } print }' txt

产生相同的输出。如果你想的话,我可以edit/elaborate稍后,现在我得走了! :)