How do I select certain columns with matching pattern and rest of the lines?

I want to select 2nd, 3rd columns if line has "key3" and print rest of the lines as is.

# This is my sample input
key1="val1" key2="val2" key3="val3" key4="val4"
some text some text
some text some text
key1="val1" key2="val2" key3="val3" key4="val4"
some text some text
some text some text
# Expected output.
key2="val2" key3="val3"
some text some text
some text some text
key2="val2" key3="val3"
some text some text
some text some text

I have this so far which is not working. How do I add second condition?

 
awk '(/key3/ {print $2" "$3}) || ({print $0})'

You've shown us the input you have, you've shown us a program that doesn't do what you want... How about you show us the output you do want? Otherwise we're left guessing.

If I correctly understand what you're trying to do (and I am not at all sure that I do), try:

awk '/key2/ || /key3/{print $2,$3; next}1' file

or:

awk '/key[23]/{print $2,$3; next}1' file

As always, if you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .

1 Like

Thanks Don your code works for me.