The usage of pipe in AWK

假装没事ソ 提交于 2019-12-03 16:31:49

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

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

try this:

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

The only problem is with your print statement. Use

print "result=" result;

(No $ on result)

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!