【问题标题】:Add info to output -- obtained from a shell command execution将信息添加到输出——从 shell 命令执行中获得
【发布时间】:2016-06-20 03:56:10
【问题描述】:

我有包含缩进行的文件,例如:

table 't'
  field 'abc'
  field 'def' and @enabled=true
  field 'ghi'
table 'u'

我想把它改成:

table 't'
  field 'abc' [info about ABC]
  field 'def' [info about DEF] and @enabled=true
  field 'ghi' [info about GHI]
table 'u'

括号之间的字符串是通过调用 shell 脚本(get-info,获取术语“abc”、“def”和“ghi”的定义)获取的。

我尝试使用 AWK(通过 cmd | getline output 机制):

awk '$1 == "field" {
    $2 = substr($2, 2, length($2) - 2)
    cmd = "get-info \"" $2 "\" 2>&1 | head -n 1" # results or error
    while (cmd | getline output) {
        print $0 " [" output "]";
    }
    close(cmd)
    next
}
// { print $0 }'

但它不尊重缩进!

我怎样才能实现我的愿望?

【问题讨论】:

  • 您的问题非常不清楚。或许添加您的 awk 脚本将有助于澄清您卡在哪里。
  • 我试图更清楚地表达我的要求。希望这会有所帮助!

标签: shell awk sed cmd getline


【解决方案1】:

看起来你想要做的是:

$1 == "field" {
    cmd = "get-info \"" substr($2,2,length($2)-2) "\" 2>&1" # results or error
    if ( (cmd | getline output) > 0 ) {
        sub(/^[[:space:]]*[^[:space:]]+[[:space:]]+[^[:space:]]+/,"& ["output"]")
    }
    close(cmd)
}
{ print }

请注意,您不需要head -1,只是不要循环读取输出。

例如:

$ cat tst.awk
$1 == "field" {
    cmd = "echo \"--->" substr($2,2,length($2)-2) "<---\" 2>&1"
    if ( (cmd | getline output) > 0 ) {
        sub(/^[[:space:]]*[^[:space:]]+[[:space:]]+[^[:space:]]+/,"& ["output"]")
    }
    close(cmd)
}
{ print }

$ awk -f tst.awk file
table 't'
  field 'abc'
  field 'def' [--->def<---] and @enabled=true
  field 'ghi'
table 'u'

在这种情况下使用getline 可能是合适的,但如果您正在考虑再次使用getline,请确保您阅读并理解http://awk.info/?tip/getline 处的所有getline 警告。

【讨论】:

  • 除了“完美!”我还能说什么?非常感谢head -1...
猜你喜欢
  • 2020-03-25
  • 2014-06-29
  • 1970-01-01
  • 2022-11-30
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
  • 2019-02-18
相关资源
最近更新 更多