如何使用shell脚本从第二列中选择值?

时间:2016-11-17 18:25:21

标签: bash shell awk scripting

如果我有一个文本文件:

MachineName    IPAddress
Computer1234   10.0.1.1
Computer1235   10.0.1.2
Computer1236   10.0.1.3

从计算机中获取MachineName后,如何从上面的文本中获取相应的IPAddress?

(bash?)脚本将在Mac上运行,上面的文本可以重新格式化和/或插入脚本本身(大约110台计算机)......

2 个答案:

答案 0 :(得分:4)

这就是awk的用途:按模式搜索字段然后执行一些操作。基本理念是

awk '/pattern/ {action}' file

在你的情况下

awk '/Computer1234/ { print $2 }' file

事实上,使用一般的awk用例

可能更具体
awk 'condition { action }' file

awk '$1 == "Computer1234" { print $2 }' file

答案 1 :(得分:0)

使用grep使其非常直接。

grep 'Computer1234' text_file.txt | awk '{print $2}'

然而,我们可以做得更好,只使用awk。

awk -v hostname='Computer1234' '$1 ~ hostname {print $2}' text_file.txt

-v var_name=是你传递awk变量的方法。

$1 ~ hostname查看第一个字段是否包含与hostname变量匹配的模式,如果是,我们打印ip!