linux - 如何比较bash中的2个文件并将特定值重定向到新文件

标签 linux bash awk sed

我有 2 个文件,比如 testtest1,输出如下:

test                      test1
abcd;india                abcd
efgh;india
ijkl;us
mnop;us

比较 testtest1 并将区域信息从测试文件重定向到新文件(比如 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/

相关文章:

linux - 执行应用程序后运行 shell 脚本命令

linux - insmod : error inserting 'usb338x.ko' : -1 Unknown symbol in module

linux - 如果找到特定模式,AWK 或 sed 需要从输出中删除行

linux - 如何打印命令的结果以及结果的计数?

shell - 根据命令行中的列拆分 csv 文件

linux - Nmap grep 和 awking 结果

linux - 如何在shell脚本中获取文件的扩展名

linux - 我在哪里可以找到 libnautilus 的文档?

linux - CircleCI:执行本地二进制文件

bash - 为什么这个 For 循环与 Bash 中的这个 While 循环不同?