0

I'm trying to develop a VARIATION of the following straightforward awk one-liner (which currently works for matching a couple of conditions in each line of a file):

awk "{ if ($1 == $3 && $2 == $7) print $1,$2}" input.txt > out.txt

The variation I need will look across all instances of two consecutive lines, instead of just a single line. So if the first line is A and the second line is B, it would look something like, say,

awk "{ if (A$1 == B$3 && A$2 == B$7) print A$1,B$1,A$2,B$2}" input.txt > out.txt

That sort of thing! An input file example would be:

banana apple orange pumpkin potato tomato onion garlic
banana apple banana pumpkin potato tomato onion garlic
lemon grape banana pumpkin potato tomato apple garlic
banana apple orange pumpkin potato tomato onion garlic

It would match on lines 2 and 3, with output:

banana lemon apple grape

I'm reasonably confident awk can do this, and I've seen what I think are the necessary building blocks, in related questions and answers on here, but I don't really have the skill to compile it properly.

0
2

You could save the fields of the previous line in an array a and access the fields of the current line prefixed with $ as usual.

awk '
 a[1]==$3 && a[2]==$7{ print a[1],$1,a[2],$2 }
 { for (i=1;i<=NF;i++) a[i]=$i }
' input.txt > out.txt
1
  • Thanks @Freddy, works well. – Simonmdr Jun 18 '20 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.