Moving a column across a delimited data file

Hi,
I am trying to move a column from one position to another position in a delimited file. The positions are dynamic in nature and are available by environmental variables. Also the file can have n number of columns.

Example:
Initial Column Position=1
Final Column Position=3
Delimiter='|'

Input:

Col1|Col2|Col3|Col4|Col5
a1|b1|c1|d1|e1
a2|b2|c2|d2|e2
a3|b3|c3|d3|e3

Output:

Col3|Col2|Col1|Col4|Col5
c1|b1|a1|d1|e1
c2|b2|a2|d2|e2
c3|b3|a3|d3|e3

Please let me know if anybody has any solution to solve this problem.
Note: I am using KSH.
Thanks.

try using awk, it's the one command I use when working with delimited text files. a search of these forums found the following.

Hi ayan153,

Try:

$ cat infile 
Col1|Col2|Col3|Col4|Col5
a1|b1|c1|d1|e1
a2|b2|c2|d2|e2
a3|b3|c3|d3|e3
$ awk -v icp=1 -v fcp=3 -v d="|" 'BEGIN { FS=OFS=d } { column=$fcp; $fcp=$icp; $icp=column; print }' infile 
Col3|Col2|Col1|Col4|Col5
c1|b1|a1|d1|e1
c2|b2|a2|d2|e2
c3|b3|a3|d3|e3

Regards,
Birei

1 Like