The usage of pipe in AWK

Aidy picture Aidy · Mar 11, 2013 · Viewed 37.9k times · Source

What I want is to get the reversed string of current line, I tried to use the rev command in the AWK but cannot get the current result.

$ cat myfile.txt
abcde

$ cat myfile.txt | awk '{cmd="echo "$0"|rev"; cmd | getline result;  print "result="$result; close(cmd);}'
abcde

I want to get edcba in the output.

I know there are some other ways to get the reversed string like $ cat myfile.txt | exec 'rev'. Using AWK here is because there are some other processes to do.

Did I miss anything?

Answer

Chris Seymour picture Chris Seymour · Mar 11, 2013

The system function allows the user to execute operating system commands and then return to the awk program. The system function executes the command given by the string command. It returns, as its value, the status returned by the command that was executed.

$ cat file
abcde

$ rev file
edcba

$ awk '{system("echo "$0"|rev")}' file
edcba

# Or using a 'here string'
$ awk '{system("rev<<<"$0)}' file
edcba

$ awk '{printf "Result: ";system("echo "$0"|rev")}' file
Result: edcba

# Or using a 'here string'
$ awk '{printf "Result: ";system("rev<<<"$0)}' file
Result: edcba