繁体   English   中英

从两个文件打印公共行 - Bash

[英]Print common line from two files - Bash

我有两个文件,我想在每一行中找到共同的第一列,并打印 file1.txt 的第一和第二列以及 file2.txt 的第二列。

file1.txt
A10 Unix
A20 Windows
B10 Network
B20 Security

file2.txt
A10 RedHat
A21 Win2008
B11 Cisco
B20 Loadbalancing

结果:

file.txt
A10 Unix RedHat
B20 Security Loadbalancing

我尝试了下面的代码但没有检索到正确的结果:

$ awk 'NR==FNR {a[$1]=$1; next} $1 in a {print a[$1], $0}' file1.txt file2.txt

这是join的标准用例,因为文件已按排序顺序。 无需任何其他代码。

$ join file1 file2

A10 Unix RedHat
B20 Security Loadbalancing
$ awk 'NR==FNR{a[$1]=$2;next} $1 in a{print $0, a[$1]}' file2 file1
A10 Unix RedHat
B20 Security Loadbalancing

您可以使用以下awk命令:

awk 'NR==FNR{a[$1]=$2} NR>FNR && $1 in a{print $1,a[$1],$2}' file1.txt file2.txt

在多行版本中有更好的解释:

# Number of record is equal to number of record in file.
# True as long as we are reading file1
NR==FNR {
    # Stored $2 in an assoc array index with $1
    a[$1]=$2
}

# Once we are reading file2 and $1 exists in array a
NR>FNR && $1 in a {
    # print the columns of interest
    print $1, a[$1], $2
}

我想从 bash 中的两个不同文件中获取常用词

不是一句台词,而是常用词。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM