2016-03-06 114 views
1

我有一个包含缩进的行诸如文件:添加信息到输出 - 从shell命令执行获得

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 }' 

,但它不尊重压痕!

我怎么能实现我的愿望?

+1

你的问题是非常不清楚的。也许增加你的Awk脚本将有助于澄清你卡住的地方。 – tripleee

+0

我试图更清楚地表达我的要求。希望这可以帮助! – user3341592

回答

0

它看起来就像你正在试图做的是什么:

$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考虑。

+1

除了“完美!”我还能说些什么?并且非常感谢'head -1'上添加的注释...... – user3341592