The usage of pipe in AWK
Asked Answered
M

5

10

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?

Meggs answered 11/3, 2013 at 11:17 Comment(0)
T
7

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
Tinney answered 11/3, 2013 at 11:32 Comment(0)
C
5

try this:

awk '{ cmd="rev"; print $0 | cmd; close(cmd) }' myfile.txt

Cofer answered 5/11, 2013 at 7:5 Comment(0)
F
1

Calling the rev command from awk is very inefficient as it creates a sub-process for each line processed. I think you should define a rev function in awk:

$ cat myfile.txt | awk 'function rev(str) {
    nstr = ""
    for(i = 1; i <= length(str); i++) {
      nstr = substr(str,i,1) nstr
    }
    return nstr
  }
  {print rev($0)}'
edcba
Freehold answered 11/3, 2013 at 13:51 Comment(1)
Redirection to a file or a command from awk does not create that file or run the process for every line, although one might easily think so: gnu.org/software/gawk/manual/html_node/Redirection.html .Elaterite
W
1

Why not

awk '{print "result =",$0}' <(rev file)

or if you are not using bash / ksh93 :

rev file | awk '{print "result =",$0}'

---

Or if your awk supports the empty FS option:

awk '{res=x; for(i=NF; i>=1; i--) res=res $i; print res}' FS= file
Wildfire answered 11/3, 2013 at 16:15 Comment(1)
Thanks for your reply, and it all works in my Bash, and good to know that it can set empty delimiter in awk.Meggs
D
0

The only problem is with your print statement. Use

print "result=" result;

(No $ on result)

Delve answered 11/3, 2013 at 12:37 Comment(1)
Yes, it worked after removing the sign $. Why it gets the content from file when using $result in print?Meggs

© 2022 - 2024 — McMap. All rights reserved.