Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse everything after the second line with AWK

Tags:

bash

awk

I'm looking for a way to ignore the first two lines of a file, and flip the ips/dns' of everything after the second line. Please note that I sed remove first line (which is a header).

bash-4.4$ less test
  1 #remove
  2 #comment 1
  3 #comment 2
  4 foo 127.0.0.1
  5 bar 127.0.0.1

the results I am looking for are

bash-4.4$ less test-fixed
  1 #comment 1
  2 #comment 2
  3 127.0.0.1 foo
  4 127.0.0.1 bar

the command pipe I've been trying is:

FILE=/tmp/test ; sed '1d' $FILE | awk 'NR>2 { t = $1; $1 = $2; $2 = t; print; } ' >| /tmp/test-fixed

obviously NR>2 ordinal number of the current record and skips to line 3 so I'm thinking I need an iteration loop to print them but not operate until N3 is reached? Not sure...

like image 419
ehime Avatar asked Jan 02 '23 21:01

ehime


1 Answers

You can use awk like this:

awk 'NR>3{s=$NF; $NF = $(NF-1); $(NF-1) = s} 1' file

1 #remove
2 #comment 1
3 #comment 2
4 127.0.0.1 foo
5 127.0.0.1 bar
like image 147
anubhava Avatar answered Jan 10 '23 17:01

anubhava