BladeSystem Forums Have Moved here
To make BladeSystem information easier to find, we have moved the BladeSystem forums here, to Servers and Operating Systems.
Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

swap the last 2 fields

SOLVED
Go to Solution
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
Acclaimed Contributor

Re: swap the last 2 fields

Hi Sathis:

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

Regards!

...JRF...
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...
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
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.
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
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