Simpler Navigation for Servers and Operating Systems
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
cancel
Showing results for 
Search instead for 
Did you mean: 

swap the last 2 fields

SOLVED
Go to solution
sathis kumar
Frequent Advisor

swap the last 2 fields

Hello,

I need to swap the last 2 fields in every line.
Input File :
B L1983A B1N 20090701 A QBL1
B L1985A 20090701 A QBL1

Output File should be:
B L1983A B1N 20090701 QBL1 A
B L1985A 20090701 QBL1 A

Could somebody let me know if this can be done using awk?

Thanks & Regards,
Sathis Kumar.B
6 REPLIES
James R. Ferguson
Acclaimed Contributor
Solution

Re: swap the last 2 fields

Hi Sathis:

# awk '{X=$NF;Y=$(NF-1);$(NF-1)=X;$NF=Y;print}' file

Regards!

...JRF...
Mel Burslan
Honored Contributor

Re: swap the last 2 fields

cat my file | while read line; do
echo $line|awk {'print $1" "$2" "$3" "$5" "$4'}
done

provided all lines have exactly 5 fields.
________________________________
UNIX because I majored in cryptology...
VK2COT
Honored Contributor

Re: swap the last 2 fields

Hello,

Of course it can be done.

You need to use for loop:

awk '{for (i=1; i<=NF-2; ++i) printf "%s ", $i; print $(NF), $(NF-1)}' filename

This worked fine on my Linux server at home.

Cheers,

VK2COT
VK2COT - Dusan Baljevic
Ganesan R
Honored Contributor

Re: swap the last 2 fields

Hi,

There are more than a way always. If the line lenths(field) are varied use this for loop. Assuming the file name is /tmp/test.txt

for A in `cat /tmp/test.txt`
do
echo $A | awk '{tmp = $NF; $NF = $(NF-1); $(NF-1) = tmp; print }' >> /tmp/test1.txt
done

Now you have the desired output in /tmp/test1.txt

Best wishes,

Ganesh.
OldSchool
Honored Contributor

Re: swap the last 2 fields

Mel B said:
cat my file | while read line; do
echo $line|awk {'print $1" "$2" "$3" "$5" "$4'}
done


you can eliminate the cat, while loop and echo. simply

awk '{print $1" "$2" "$3" "$5" "$4'} old_file > new_file

lets awk do the read and it will loop for every line in the original file
Highlighted
OldSchool
Honored Contributor

Re: swap the last 2 fields

I should have noted the same for Ganesan's. it simplifies to:

awk '{tmp = $NF; $NF = $(NF-1); $(NF-1) = tmp; print }' /tmp.test >> /tmp/test1.txt