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.
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
Remove the dollar sign in front of myvar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With