[英]How to print the result of a system command in awk
I have the following single line in my bash script:我的 bash 脚本中有以下单行:
echo "foo" | awk -F"=" '{char=system("echo $1 | cut -c1");}{print "this is the result: "$char;}' >> output.txt
I want to print the first letter of "foo" using awk, such that I would get:我想使用 awk 打印“foo”的第一个字母,这样我会得到:
this is the result: f
in my output file, but instead, I get:在我的 output 文件中,但相反,我得到:
this is the result: foo
What am i doing wrong?我究竟做错了什么? Thanks谢谢
No, this is not the way system
command works inside awk
.不,这不是system
命令在awk
中工作的方式。
What's happening in OP's code: OP的代码中发生了什么:
system
which is good(for some cases) but there is a problem in this one that you should give it like system("echo " $0" | cut -c1")
to get its first character AND you need NOT to have a variable etc to save its value and print it in awk
.您在system
中给出了一个 shell 命令,这很好(在某些情况下),但是在这个命令中存在一个问题,您应该像system("echo " $0" | cut -c1")
一样给出它来获取它的第一个字符和你不需要有变量等来保存其值并将其打印在awk
中。shell
style in awk
in here.它不像awk
中的shell
风格在这里工作。char
will have 0
value(which is a success status from system
command) and when you are printing $char
it is printing whole line(because in awk
: print $0
means print whole line).因此,名为char
的变量将具有0
值(这是system
命令的成功状态),当您打印$char
时,它正在打印整行(因为在awk
中: print $0
表示打印整行)。 You could do this in a single awk
by doing:您可以通过以下方式在单个awk
中执行此操作:
echo "foo" | awk '{print substr($0,1,1)}'
OR with GNU awk
specifically:或者使用 GNU awk
特别是:
echo "foo" | awk 'BEGIN{FS=""} {print $1}'
you're not using much of awk
, same can be done with printf
您没有使用太多awk
,同样可以使用printf
$ echo "foo" | xargs printf "this is the result: %.1s\n"
this is the result: f
or, directly或者,直接
$ printf "this is the result: %.1s\n" foo
this is the result: f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.