简体   繁体   English

如何在 awk 中打印系统命令的结果

[英]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的代码中发生了什么:

  • You are giving a shell command in 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中。
  • You are trying to save its result to a variable but it will not have its value(system command's value) but its status.您正在尝试将其结果保存到一个变量中,但它不会有它的值(系统命令的值),而是它的状态。 It doesn't work like shell style in awk in here.它不像awk中的shell风格在这里工作。
  • So your variable named 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM