5

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.

David Parks
  • 30,789
  • 47
  • 185
  • 328

2 Answers2

7

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
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • +1 another common way to think of `$` is as the name of an array of fields. It kinda falls apart syntactically but functionally it's not a bad analogy. – Ed Morton Jun 05 '14 at 22:21
2

Remove the dollar sign in front of myvar

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432