awk添加以前发起的变量bash

时间:2015-04-23 08:54:29

标签: bash variables printing awk

我在向AWK添加变量时遇到了问题。

我有一个包含以下输入的文件:

MainComputer>
Device ID: name1
Interface: 1
random text...
Device ID: name2
Interface: 2
random text....
Device ID: name3
Interface: 3
random text....

现在我要打印所有变量:我已经拥有的东西:

#!/bin/bash
line=$(head -n 1 file)
var=$(echo $line | cut -d ">" -f1)
var2=$(awk '/Interface/  {print $2}' file)  
awk -v var3="$var" '/Device/ {print var3, "->", $2, "[Label: "$var2"]}' file

但是$ var2并没有显示输出,如果我把:var2它给出了一个错误。

我想要的输出:

MainComputer -> name1 [Label: 1]
MainComputer -> name2 [Label: 2]
MainComputer -> name3 [Label: 3]

等其他40个输入....

但它只给MainComputer - > name1和接口标签上的错误......

所以我正在寻找一种打印超过1 var的方法,我已经初始化了。

非常感谢!

1 个答案:

答案 0 :(得分:1)

如果我理解你正在尝试做什么,那么在纯awk中可以更好地实现:

awk -F ': *' 'NR == 1 { sub(/>.*/, ""); name = $0; next } $1 == "Device ID" { dev = $2 } $1 == "Interface" { print name " -> " dev " [Label: " $2 "]" }' file

-F ': *'将字段分隔符设置为正则表达式: *(匹配冒号后跟任意数量的空格)。代码的工作原理如下:

NR == 1 {           # in the first line:
  sub(/>.*/, "")    # remove > and everything after it
  name = $0         # remember as machine name
  next              # do nothing else
}
$1 == "Device ID" { # after that: In device lines
  dev = $2          # remember device name
}
                    # In interface lines: print remembered info
$1 == "Interface" {
  print name " -> " dev " [Label: " $2 "]"
}

这将按照您在问题中显示的方式显示文件中的所有行。如果要筛选特定行,可以按如下方式进行修改:

awk -v filter="name2" -F ': *' 'NR == 1 { sub(/>.*/, ""); name = $0; next } $1 == "Device ID" { dev = $2 } $1 == "Interface" && dev == filter { print name " -> " dev " [Label: " $2 "]" }' file

也就是说,使用filter使awk知道变量-v filter=value,然后修改代码

NR == 1 {
  sub(/>.*/, "")
  name = $0
  next
}
$1 == "Device ID" {
  dev = $2     
}
$1 == "Interface" && dev == filter {         # <-- here
  print name " -> " dev " [Label: " $2 "]"
}