Shell脚本:删除grep匹配行前4行中#开头的注释行
AWK命令条件补充方案
问题背景
现有test.txt文件内容:
sample #comment jacuzzi #comment testing it was the the age of wisdom4,
需求:匹配所有以te开头的行,删除该行前4行中以#开头的注释行,最终输出:
sample jacuzzi testing it was the the age of wisdom4,
用户已编写基础AWK命令,需完善条件判断部分:
awk 'NR==FNR{if (/^te.*/) for (i=-4;i<=0;i++) if (what to write here?) del[NR+i]; next} !(FNR in del)' test.txt
补充后的完整命令
NR==FNR{ line[NR] = $0 if (/^te/) { for (i=-4; i<=0; i++) { target = NR + i if (target >= 1 && line[target] ~ /^#/) { del[target] } } } next } !(FNR in del)
逻辑说明
- 第一遍扫描文件时,将每行内容存入
line数组,行号作为索引 - 当匹配到以
te开头的行时,遍历该行前4行到自身的行号范围 - 先判断目标行号是否合法(避免小于1的越界情况),再检查该行是否以
#开头,满足条件则将该行号加入del标记数组 - 第二遍扫描时,仅输出未被标记删除的行
内容的提问来源于stack exchange,提问作者Arham Jain
相关产品推荐
相关产品推荐

