Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a string (line) in an AWK variable

Tags:

awk

Writing an AWK script, I want to store a line I find in a variable, and only later, if I also match another line, print out that original line.

Example:

a    <-- save this one
b
c    <-- Now that we found c, let's print a

Psudo, wish-it-worked-exactly-like-this, code:

/a/ { myvar = $0 }
/c/ { print $myvar $0 }

In dreamland produces:

ac

Actual, psychedelic, results of my wishful-thinking psudo code:

cc

Note: it's cheating to answer "just print a, then c as would work with a simplification of this example. The real-world use case calls for c only being printed based on further conditions, thus the need to store the most recently seen a on the chance a following c will be printed.

like image 975
David Parks Avatar asked Jun 05 '14 21:06

David Parks


2 Answers

working code

/a/ { myvar = $0 }
/c/ { print myvar $0 }

Think of $ as an operator, that fetches the value of the given field number.

Here myvar holds the value "a". A string that does not begin with digits is considered to have the value zero, when taken in a numeric context. Thus, $myvar is seen as $"a" which is $0

A strange way to take advantage of this:

awk '/a/ {myvar = $0} /c/ {print $myvar $1}' <<END
2a
b
c d
END

will output

dc
like image 59
glenn jackman Avatar answered Sep 24 '22 15:09

glenn jackman


Remove the dollar sign in front of myvar

like image 23
Mark Setchell Avatar answered Sep 22 '22 15:09

Mark Setchell