Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK -- How to assign a variable's value from matching regex which comes later?

Tags:

variables

awk

While I have this awk script,

/regex2/{
var = $1}

/regex1/{
print var}

which I executed over input file:

regex1

This should be assigned as variable regex2

I got no printed output. The desired output is: "This" to be printed out.

I might then think to utilize BEGIN:

BEGIN{
/regex2/
var = $1}

/regex1/{
print var}

But apparently BEGIN cannot accommodate regex matching function. Any suggestion to this?

like image 267
nawesita Avatar asked Dec 17 '25 18:12

nawesita


1 Answers

This would achieve the desired result:

awk '/regex2/ { print $1 }'

Otherwise, you'll need to read the file twice and perform something like the following. It will store the last occurrence of /regex2/ in var. Upon re-reading the file, it will print var for each occurrence of /regex1/. Note that you'll get an empty line in the output and the keyword 'This' on a newline:

awk 'FNR==NR && /regex2/ { var = $1; next } /regex1/ { print var }' file.txt{,}
like image 121
Steve Avatar answered Dec 19 '25 18:12

Steve