Issue
I need to place cells of every 2nd and 3rd column in sorted order. Thus, I need to swap X[N][2] and X[N][3] if X[N][2] > X[N][3], where X - matrix, N - any natural number I have a table file like this:
A 9 1 2
B 8 7 F
C 2 4 X
D 3 1 1
I need to get this:
A 1 9 2
B 7 8 F
C 2 4 X
D 1 3 1
So line order remained the same, but some cells X[i][2] and X[i][3] got swapped.
I thought about using pipeline with xargs cut and sort but it doesn't seem to be a good idea. Any suggestions where to dig?
Solution
This can be solved with a small awk script:
# Swap X[N][2] and X[N][3] if X[N][2] > X[N][3]
$2 > $3 {
tmp = $3
$3 = $2
$2 = tmp
}
# Print row
1
To use it in a script or shell as a one-liner: awk '$2 > $3 { tmp = $3; $3 = $2; $2 = tmp } 1' inputfile.txt
Answered By - shilch