Re: swap the last 2 fields (241 Views)
Reply
Frequent Advisor
sathis kumar
Posts: 56
Registered: ‎08-21-2006
Message 1 of 7 (241 Views)
Accepted Solution

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
Acclaimed Contributor
James R. Ferguson
Posts: 21,184
Registered: ‎07-06-2000
Message 2 of 7 (241 Views)

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
Mel Burslan
Posts: 3,214
Registered: ‎08-26-1998
Message 3 of 7 (241 Views)

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
VK2COT
Posts: 921
Registered: ‎01-17-2006
Message 4 of 7 (241 Views)

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
Ganesan R
Posts: 1,891
Registered: ‎05-23-2006
Message 5 of 7 (241 Views)

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
OldSchool
Posts: 3,372
Registered: ‎09-09-2004
Message 6 of 7 (241 Views)

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
Honored Contributor
OldSchool
Posts: 3,372
Registered: ‎09-09-2004
Message 7 of 7 (241 Views)

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
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.