0

I have input file

ABC 123      DEF  456
ZYX 098      WVU  765
PQR 111      RST  333

Now I am trying to display 3rd and 4th Column if pattern matches in column 1, and display 1st and 2nd column if patter matches on 3rd column.

awk '{{for(i=1;i<=NF;i++)if($i == "ABC") printf $(i+2)" "$(i+3)" "} print ""; }'

This does the job but input will be a variable as in so I don't know if it will match on column 1 or column 3.

x=ABC or x=DEF 
awk -v x="$x" '{{for(i=1;i<=NF;i++)if($i==x) printf $(i+2)" "$(i+3)" "} print ""; }' 

(Depending upon the input value of x, so if I can compare Field no as well it should do the job)

Expected Output if x=ABC

DEF  456

if x=DEF

ABC 123

And so on for each line....

  • What's the expected output here ? – don_crissti Mar 2 '17 at 12:25
  • 1
    KISS: '$1 == x || $2 == x {print $3, $4} $3 == x {print $1, $2}' – steeldriver Mar 2 '17 at 12:27
  • @don_crissti Updated my question. – Sid Mar 2 '17 at 12:42
  • 1
    as suggested awk -vx="$x" '$1 == x {print $3, $4} $3 == x {print $1, $2}' – don_crissti Mar 2 '17 at 12:54
  • @don_crissti It did the job, thanks. Any other option you can think of? Post an answer so I can select it as answer – Sid Mar 3 '17 at 9:59
1
awk -vx="$x" '$1 == x {print $3, $4} $3 == x {print $1, $2}'

@don_crissti This seems to do the job just fine.

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.