AWK – Print Certain Lines Without Processing

awktext formattingtext processing

If I had a file in the following format:

line1 column1
line2 columnA
line3 column1A
exclude this
line5 column2
line6 columnB
line7 column2B

I want to swap the columns, so column* gets printed before line*. I use a simple awk command like this: awk '{print $2 " " $1}' and get an output like this:

column1 line1
columnA line2
column1A line3
this exclude
column2 line1
columnB line2
column2B line3

now I want the line with exclude to be printed but not resorted (it is not necessarily line 3). I could use this command to ignore the lines: awk '/exclude/{next}{print $2 " " $1}' and I get an output without the excluded line:

column1 line1
columnA line2
column1A line3
column2 line1
columnB line2
column2B line3

How can I tell awk to print those line containing exclude but not resort the columns? So I would get an output like this:

column1 line1
columnA line2
column1A line3
exclude this
column2 line1
columnB line2
column2B line3

Best Answer

Something like

awk '{if(/exclude/){print}else{print $2,$1}}' file.txt

Or, same result, but a little shorter.

awk '!/exclude/{$0=$2FS$1}1' file.txt
Related Question