将信息添加到输出——从 shell 命令执行中获得
Add info to output -- obtained from a shell command execution
我有包含缩进行的文件,例如:
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 ' == "field" {
= substr(, 2, length() - 2)
cmd = "get-info \"" "\" 2>&1 | head -n 1" # results or error
while (cmd | getline output) {
print [=13=] " [" output "]";
}
close(cmd)
next
}
// { print [=13=] }'
但它不尊重缩进!
如何实现我的愿望?
看起来你想做的是:
== "field" {
cmd = "get-info \"" substr(,2,length()-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
== "field" {
cmd = "echo \"--->" substr(,2,length()-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
再一次。
我有包含缩进行的文件,例如:
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 ' == "field" {
= substr(, 2, length() - 2)
cmd = "get-info \"" "\" 2>&1 | head -n 1" # results or error
while (cmd | getline output) {
print [=13=] " [" output "]";
}
close(cmd)
next
}
// { print [=13=] }'
但它不尊重缩进!
如何实现我的愿望?
看起来你想做的是:
== "field" {
cmd = "get-info \"" substr(,2,length()-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
== "field" {
cmd = "echo \"--->" substr(,2,length()-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
再一次。