Reputation: 4050
Given the following in a file, file.txt
:
Line with asdfgh output1 45 output2 80
Special Header
Line with output1 38 output2 99
Special Header
I would like to print to a file:
45 80
38 99
i.e., in the line immediately preceding lines whose first column is Special
, store the number (which can be a float
type with decimals) after output1
and output2
I tried:
awk '($1 == "Special" ) {printf f; printf ("\n");} {f=$0}' file.txt > output.txt
This captures the entirety of the previous line and I get output.txt
which looks like this:
Line with output1 45 output2 80
Line with output1 38 output2 99
Now, within the captured variable f
, how can I access the specific values after output1
and output2
?
Upvotes: 1
Views: 64
Reputation: 203229
$ awk '$1=="Special"{print x, y} {x=$(NF-2); y=$NF}' file
45 80
38 99
Upvotes: 1
Reputation: 23667
With GNU awk
:
$ awk '$1=="Special"{print m[1], m[2]}
{match($0, /output1\s+(\S+).*output2\s+(\S+)/, m)}' ip.txt
45 80
38 99
With perl
:
$ perl -ne 'print "@d\n" if /^Special/; @d = /output[12]\s+(\S+)/g' ip.txt
45 80
38 99
Upvotes: 1
Reputation: 185015
Like this:
$ awk '{for (i=1; i<NF; i++)
if ($i == "output1") {arr[NR]=$(i+1)}
else if ($i == "output2") {arr[NR]=arr[NR]" "$(i+1)}}
($1 == "Special") {print arr[NR-1]}
' file
45 80
38 99
Upvotes: 1