【问题标题】:match the string in a file and print the next column匹配文件中的字符串并打印下一列
【发布时间】:2016-02-27 02:14:26
【问题描述】:

我有两个文件 input1.txt 和 input2.txt。

input1.txt 有以下详细信息:

abcd.net
bcad.net
cagh.net
degh.net
usna.net

input2.txt 有以下详细信息:

abcd.net 169.254.0.2
bcad.net 169.254.0.3
cagh.net 169.254.0.4
us-1212-qwe.net 169.254.232.50
us-cisco.net 10.120.2.3
degh.net 169.254.0.5
usna.net 169.254.0.6
ab1234.net 169.254.0.7
catorr.net 169.254.0.8

我需要从文件“input2.txt”中获取“input1.txt”中列出的服务器对应的IP详细信息

输出应该是这样的:

abcd.net 169.254.0.2
bcad.net 169.254.0.3
cagh.net 169.254.0.4
degh.net 169.254.0.5
usna.net 169.254.0.6

我的代码如下所示不能正常工作。请帮忙。

  for i in `cat input1.txt`; do more input2.txt | grep -w "^$i"; done

【问题讨论】:

标签: awk grep


【解决方案1】:
awk 'FNR==NR{ip[$1]=$2} FNR!= NR {print $1, ip[$1]}' input2.txt input1.txt

这会读取 input2.txt 并构建所需数据的数组,由第一列索引。然后它读取 intput1.txt 并为每一行打印主机和数组中的数据。

请注意,上面给出的答案不再适用,因为问题已被编辑。对于已编辑的问题,您可以:

 awk 'FNR==NR{ip[$1".net"]=$2} FNR!= NR {print $1, ip[$1]}' input2.txt input1.txt

但这不是最好的通用解决方案。 (例如,硬编码文本“.net”是一种糟糕的方法,但对于快速破解来说,这很好。)

【讨论】:

  • 或者取消复制然后否定条件:FNR==NR{ip[$1]=$2;next} {print $1, ip[$1]}。 @user3834663 这绝对是基本的 awk - 阅读 Arnold Robbins 撰写的 Effective Awk Programming,第 4 版的前几章以了解此脚本,然后在尝试任何更多的 shell 编程之前完成阅读。
  • 以类似的方式,如果 input1.txt 只有下面的短名称。我该怎么搭配? abcd bcad cagh degh usna
  • @user3834663 我不明白你的问题。你问的是input1.txt都在一行的情况吗?
  • input1.txt 的短名称没有“.net”,我需要通过比较 input2.txt 在 output.txt 中得到相同的结果
  • 您编辑了问题,因此我的回答不再有效!不要那样做。
【解决方案2】:

awk的替代品

join <(sort input1) <(sort input2)

abcd.net 169.254.0.2
bcad.net 169.254.0.3
cagh.net 169.254.0.4
degh.net 169.254.0.5
usna.net 169.254.0.6

或者好旧的grep

grep -f input1 input2

abcd.net 169.254.0.2
bcad.net 169.254.0.3
cagh.net 169.254.0.4
degh.net 169.254.0.5
usna.net 169.254.0.6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2019-05-04
    相关资源
    最近更新 更多