简体   繁体   中英

How to print the result of a system command in awk

I have the following single line in my bash script:

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:

this is the result: f

in my output file, but instead, I get:

this is the result: foo

What am i doing wrong? Thanks

No, this is not the way system command works inside awk .

What's happening in OP's code:

  • 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 .
  • 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.
  • 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).


You could do this in a single awk by doing:

echo "foo" | awk '{print substr($0,1,1)}'

OR with GNU awk specifically:

echo "foo" | awk 'BEGIN{FS=""} {print $1}'

you're not using much of awk , same can be done with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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