如何使用一个命令将两个命令的输出合并为一个?
命令1输出:
ID NAME1 COLUMN2
xxx-1 aaa bbb
xxx-2 ccc ddd
xxx-3 eee fff
xxx-4 nnn mmm
命令2输出:
COLUMN3 COLUMN4 ID
kkk www xxx-3
kkk ppp xxx-1
kkk qqq xxx-4
lll ttt xxx-2
kkk rrr xxx-2
注意:command1 xxx-2
返回ccc
(NAME1 字段)
预计屏幕上会出现一个命令和替换,不涉及任何文件。
预期结果:
COLUMN3 COLUMN4 NAME1
kkk www eee
kkk ppp aaa
kkk qqq nnn
lll ttt ccc
kkk rrr ccc
非常感谢。
**
** 编辑:添加了 2 个哑脚本,其中包含每个命令的结果以进行测试。
命令1.sh >
#!/bin/sh
if [[ -z "$1" ]]; then
echo 'ID NAME1 COLUMN2
3cc45fe6-gqee-321f-c143-w3d1d278912c aaa bbb bab bab
4a39466b-211d-48e2-a86b-db022c10fe59 ccc ddd ddd daa ddd
adw45fe6-fqxe-261g-k172-a7d1x277112d eee fff fff
f28894d0-cf40-4cff-a19a-a6893f88dd67 nnn mmm mamm mmm'
elif [[ -n "$1" ]]; then
if [[ "$1" == "3cc45fe6-gqee-321f-c143-w3d1d278912c" ]]; then
echo "aaa"
elif [[ "$1" == "4a39466b-211d-48e2-a86b-db022c10fe59" ]]; then
echo "ccc"
elif [[ "$1" == "adw45fe6-fqxe-261g-k172-a7d1x277112d" ]]; then
echo "eee"
elif [[ "$1" == "f28894d0-cf40-4cff-a19a-a6893f88dd67" ]]; then
echo "nnn"
else
echo "Error from server (NotFound)"
fi
fi
命令2.sh >
#!/bin/sh
echo 'COLUMN3 COLUMN4 ID
kkk www wwaaw www www adw45fe6-fqxe-261g-k172-a7d1x277112d
kkk pppppppppppp paaapp ppp ppp 3cc45fe6-gqee-321f-c143-w3d1d278912c
kkk qqq qqq qqqqqqqqqqqqqqq f28894d0-cf40-4cff-a19a-a6893f88dd67
lll tttttttttttt ttttttttt ttt ttt 4a39466b-211d-48e2-a86b-db022c10fe59
kkk rrrrrr rrrrrr rrrraarrrrr rrr 4a39466b-211d-48e2-a86b-db022c10fe59'
答案1
awk 'NR==FNR{a[$1]=$2; next} {$3=a[$3]} 1' <(command1) <(command2)
可能就是您正在寻找的。
我调整了上面的内容并重新运行,给出了您添加的 2 个命令脚本产生的输出:
$ awk '
NR==FNR { map[$1]=$2; next }
{ key=$NF; sub(/[^[:space:]]+[[:space:]]*$/,""); print $0 map[key] }
' <(./command1.sh) <(./command2.sh)
COLUMN3 COLUMN4 NAME1
kkk www wwaaw www www eee
kkk pppppppppppp paaapp ppp ppp aaa
kkk qqq qqq qqqqqqqqqqqqqqq nnn
lll tttttttttttt ttttttttt ttt ttt ccc
kkk rrrrrr rrrrrr rrrraarrrrr rrr ccc
我编写了它,以便映射能够工作,并且输出将保留与输入相同的间距,无论第一个输入流的第三个字段或第二个输入流的第二个字段是否有空格,或者空格是否为空格或制表符或者字段是否是固定宽度的。唯一不能包含空格的字段是输入 1 的字段 1 和 2 以及输入 2 的字段 3。