【问题标题】:Shell script to combine three files using AWK使用 AWK 组合三个文件的 Shell 脚本
【发布时间】:2012-07-10 23:44:04
【问题描述】:

我有三个文件 G_P_map.txt、G_S_map.txt 和 S_P_map.txt。我必须使用 awk 组合这三个文件。示例内容如下-

(G_P_map.txt 包含)

test21g|A-CZ|1mos
test21g|A-CZ|2mos
 ...

(G_S_map.txt 包含)

nwtestn5|A-CZ
nwtestn6|A-CZ
 ...

(S_P_map.txt 包含)

3mos|nwtestn5
4mos|nwtestn6

预期输出:

1mos, 3mos
2mos, 4mos

这是我尝试过的代码。我能够将前两个结合起来,但我不能与第三个结合起来。

awk -F"|" 'NR==FNR {file1[$1]=$1; next} {$2=file[$1]; print}' G_S_map.txt S_P_map.txt 

非常感谢任何想法/帮助。提前致谢!

【问题讨论】:

  • 第一个文件中的两行都包含 A-CZ。链接到 nwtestn5/6 的密钥是什么?

标签: bash shell awk


【解决方案1】:

我会查看joincut 的组合。

【讨论】:

  • 来自the ABCs of UnixJ 代表join,没有人使用。但这正是这里的正确工具! ^__^
【解决方案2】:

GNU AWK (gawk) 4 有 BEGINFILEENDFILE 非常适合这个。但是,gawk 手册包含一个函数,可为大多数 AWK 版本提供此功能。

#!/usr/bin/awk

BEGIN {
    FS = "|"
}

function beginfile(ignoreme) {
    files++
}

function endfile(ignoreme) {
    # endfile() would be defined here if we were using it
}

FILENAME != _oldfilename \
{
    if (_oldfilename != "")
        endfile(_oldfilename)
    _oldfilename = FILENAME
    beginfile(FILENAME)
}

END   { endfile(FILENAME) }

files == 1 {    # save all the key, value pairs from file 1
    file1[$2] = $3
    next
}

files == 2 {    # save all the key, value pairs from file 2
    file2[$1] = $2
    next
}

files == 3 {    # perform the lookup and output
    print file1[file2[$2]], $1
}    

# Place the regular END block here, if needed. It would be in addition to the one above (there can be more than one)

这样调用脚本:

./scriptname G_P_map.txt G_S_map.txt S_P_map.txt

【讨论】:

  • 不错!我看了这个问题 5 分钟,并没有想出将数据拉入数组的好方法。 Dennis,你再次教会了我一些关于 Awk 的新知识。谢谢! :-)
  • @ghoti:我修复了一些会导致错误消息的问题。
  • 您可以将FILENAME != _oldfilename 块替换为更简单的FNR == 1{files++}
  • @WilliamPursell:是的,但我提出了更通用的解决方案,如果需要可以扩展。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多