【问题标题】:Matching contents of one file with another and returning second column将一个文件的内容与另一个文件匹配并返回第二列
【发布时间】:2019-03-24 21:41:25
【问题描述】:

所以我有两个txt文件 文件1.txt

s
j
z
z
e

和file2.txt

s h
f a
j e
k m
z l
d p
e o

我想要做的是将文件 1 的第一个字母与文件 2 的第一个字母匹配并返回文件 2 的第二列。例如,例外输出将是

h
e
l
l
o

我正在尝试使用 join file1.txt file2.txt 但这只会打印出整个第二个文件。不知道如何解决这个问题。谢谢。

【问题讨论】:

  • 是否必须保持行的顺序?
  • 是的,否则我将无法得到正确的消息(“你好”)

标签: bash unix


【解决方案1】:

这是 awk 经典:

$ awk 'NR==FNR{a[$1]=$2;next}{print a[$1]}' file2 file1
h
e
l
l
o

解释:

$ awk '
NR==FNR {       # processing file2
    a[$1]=$2    # hash records, first field as key, second is the value
    next
} {             # second file
    print a[$1] # output, change the record with related, stored one
}' file2 file1

【讨论】:

  • 好吧,呃,好吧,这是呃,这是一个老歌,但是,嗯,这是一个老歌,我来自哪里,呃。好吧,伙计们,呃,听着。这是'B'中的布鲁斯即兴演奏,请注意我的变化,并尝试跟上,好吧。:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2019-11-19
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
相关资源
最近更新 更多