Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The usage of pipe in AWK

Tags:

getline

pipe

awk

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?

like image 754
Aidy Avatar asked Mar 11 '13 11:03

Aidy


People also ask

What is awk '{ print $1 }'?

awk treats tab or whitespace for file separator by default. Awk actually uses some variables for each data field found. $0 for whole line. $1 for first field. $2 for second field.

What is the pipe command in Linux?

Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on. It can also be visualized as a temporary connection between two or more commands/ programs/ processes.

What is the usage syntax of awk?

The Basic Syntax of the awk command In its simplest form, the awk command is followed by a set of single quotation marks and a set of curly braces, with the name of the file you want to search through mentioned last.

How do I use Getline in awk?

The getline command returns 1 if it finds a record and 0 if it encounters the end of the file. If there is some error in getting a record, such as a file that cannot be opened, then getline returns -1. In this case, gawk sets the variable ERRNO to a string describing the error that occurred.


2 Answers

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
like image 82
Chris Seymour Avatar answered Sep 28 '22 01:09

Chris Seymour


try this:

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

like image 31
JoeSch Avatar answered Sep 28 '22 00:09

JoeSch