我有 2 个文件,比如 test
和 test1
,输出如下:
test test1
abcd;india abcd
efgh;india
ijkl;us
mnop;us
比较 test
和 test1
并将区域信息从测试文件重定向到新文件(比如 test2
)的正确方法是什么?
test2 expected output
india
最佳答案
awk -F';' 'FNR==NR{ a[$1]=$2; next }($1 in a){ print a[$1] }' test test1
保存输出文件重定向如下所示
awk -F';' 'FNR==NR{ a[$1]=$2; next }($1 in a){ print a[$1] }' test test1 > test2
解释:
awk -F';' ' # call awk set field separator as ;
FNR==NR{ # first file "test"
a[$1]=$2; # a is array,
# $1 (col1) is array key
# $2 (col2) is array value
next # stop processing further go to next line
}
($1 in a){ # here we read file "test1"
# if array a has index which is 1st column from test1 file
print a[$1] # print array a value
}' test test1
关于linux - 如何比较bash中的2个文件并将特定值重定向到新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47587669/