Search code examples
awkcygwin

How to swap the last two column pairs with awk?


I am trying this

awk '{B=$(NF-1);A=$NF;  $NF=$(NF-2); $(NF-1) = $(NF-3); $(NF-2)=A; $(NF-3) = B; print;}' input_text.txt

but I get the error:

awk: cmd. line:1: (FILENAME=cazzo.txt FNR=2) fatal: attempt to access field -1

Sample input:

$ cat input_text.txt
1 7 9 11 0 5 2

The same happens if I replace the spaces with tabs in the input_text.txt file.

Expected output:

 1 7 9 5 2 11 0

I am running with Cygwin on Windows 10.


Solution

  • You can try this awk for swapping values:

    awk 'NF > 3 {a=$NF; b=$(NF-1); $NF=$(NF-2); $(NF-1)=$(NF-3); $(NF-3)=b; $(NF-2)=a} 1' file
    
    1 7 9 5 2 11 0
    

    If there are DOS line breaks then use:

    awk -v RS='\r?\n' 'NF > 3 {a=$NF; b=$(NF-1); $NF=$(NF-2); $(NF-1)=$(NF-3); $(NF-3)=b; $(NF-2)=a} 1' file
    

    If you have gnu awk then you can use this regex based approach:

    awk -v RS='\r?\n' 'NF > 3 {
    $0 = gensub(/(\S+\s+\S+)(\s+)(\S+\s+\S+)$/, "\\3\\2\\1", "1")} 1' file
    
    1 7 9 5 2 11 0