Walker News

How To Run Shell Command Inside Awk?

Question: Can we execute a Bash shell command or Linux program from within awk script?

Yes, by all means, via the awk I/O function called “system”.

For example, I created a script called tst, containing two lines:
date -u -d "1970-01-01 $1 secs"

Now, the awk syntax for executing the shell script tst:
echo "1356134400" | awk '{system("sh tst "$1)}'

which produce output as:
Sat Dec 22 00:00:00 UTC 2012

Interpret the syntax

1. The text in blue color is the operating system command that you want to execute. This command can be a shell script, shell command, Linux program, user program, etc.

2. The text in red color refers to first field of record, which is passed to the system command as input parameter value.

The use of awk system function call is also demonstrated in an earlier post about how to convert epoch time in DB2 SQL output. Enjoy awk scripting :)

Custom Search

  1. Emerson Prado 12-02-14@00:00

    My awk one-liners used to have:
    awk ‘{ print “command” }’ | sh
    You have just reduced them and made them more elegant. Thanks a lot!

2016  •  Privacy Policy