You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWK命令需求:指定FS与RS时提取首词并对比相邻行首词

AWK处理:对比相邻行首词并输出不匹配行

先理清楚你的需求:你已经通过find+grep等管道命令得到了结构化的输出,现在需要用AWK在FS="\n"、RS=""的设置下,把每两行作为一组(B_param行在前,A_param行在后),对比每组两行的首数字,当数字不相等时输出组内的第一行。

你的当前命令与输出

你当前的完整命令是:

find . -name 21* -path "*/path1/*" -exec grep -FHI -A 4 -we "\$dup" {} \; | egrep "(A|B)_param" | sort | uniq -c | sort -nrk 5 | awk 'BEGIN{FS ="\n"; RS = ""}{ for (i = 1; i <= NF; i++) {print i $i}}'

输出示例:

128 ./debug/21.file1.log- parameter \B_param 129
128 ./debug/21.file1.log- parameter \A_param 129
34 ./debug/21.file1.log- parameter \B_param 128
34 ./debug/21.file1.log- parameter \A_param 128
2 ./debug/21.file1.log- parameter \B_param 66
3 ./debug/21.file1.log- parameter \A_param 66
64 ./debug/21.file1.log- parameter \B_param 65
65 ./debug/21.file1.log- parameter \A_param 65
1 ./debug/21.file1.log- parameter \B_param 65
1 ./debug/21.file1.log- parameter \A_param 65

解决方案:修改AWK脚本

我们可以在AWK里完成首词提取和对比逻辑,替换你原来的AWK部分即可。核心思路是:

  • 把整个输入作为一个大记录(RS=""),每行是一个字段(FS="\n")
  • 按每两行一组遍历,提取每组两行的首数字
  • 对比数字,不相等时输出组内第一行

完整命令如下:

find . -name 21* -path "*/path1/*" -exec grep -FHI -A 4 -we "\$dup" {} \; | egrep "(A|B)_param" | sort | uniq -c | sort -nrk 5 | awk '
BEGIN {
    FS = "\n"
    RS = ""
}
{
    # 每两行一组遍历,i是每组第一行的字段索引
    for (i = 1; i <= NF; i += 2) {
        # 提取第i行的首词(第一个空格分隔的元素)
        split($i, line1, /[[:space:]]+/)
        count1 = line1[1]
        # 提取第i+1行的首词
        split($(i+1), line2, /[[:space:]]+/)
        count2 = line2[1]
        # 对比,不相等则输出第i行
        if (count1 != count2) {
            print $i
        }
    }
}'

预期输出

运行后会输出首数字不匹配的组第一行:

2 ./debug/21.file1.log- parameter \B_param 66
64 ./debug/21.file1.log- parameter \B_param 65

补充说明

  • split($i, arr, /[[:space:]]+/) 用任意空白字符拆分每行,确保能准确提取首数字(不管空格数量)
  • 循环步长设为2,刚好对应你输出里B_param和A_param的成对出现规律
  • 如果你的行对不是严格成对的,也可以调整逻辑改为遍历所有相邻行(i从1到NF-1,对比i和i+1),不过从你的示例看,成对处理更符合需求

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:05:54