bash - awk 在匹配之前删除空行之后

标签 bash awk

我没有找到完全相同的问题,所以我需要问:

我有一个文件gist :

...
must_be_intact

bad_line
bad_line
bad_line
match_line
...

我使用 awk 删除匹配之前但空格之后的所有内容:

'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并使用的行的范围>操作 block 中的下一步以跳过该部分。

关于bash - awk 在匹配之前删除空行之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71051831/

相关文章:

multithreading - Perl 或 Bash 线程池脚本?

linux - 如何使用 grep 对标题和模式进行 grep

awk - 在评估记录集时使 AWK 代码更高效

bash - 如何在 shell 上删除早于 x 秒(不是天、小时或分钟)的文件?

regex - 在 sed 或 awk 中的两个匹配项之间的最后一行之前插入文本

unix - 使用awk的小时(行)平均列数

linux - 如何使用 bash 将未知数量的源文件名拆分为指定数量的输出文件

linux - 在 bash 中读取和比较 .txt 文件中的列

linux - youtube api v3 通过 bash 和 curl 进行搜索

bash - 如何在awk中打​​印文件名?