Shell
使用一行命令替換或合併兩個命令的輸出
如何使用一個命令將兩個命令的輸出合併為一個?
命令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'
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。