Skip to main content
added 228 characters in body
Source Link
DopeGhoti
  • 79.2k
  • 10
  • 107
  • 141

To replace the fourth field with the last field:

awk -v OFS="\t" '{ $4 = $NF; $NF=""; print }

To insert the last field before the fourth field, we have to get a little creative:

awk -v OFS="\t" '{temp=$NF; for( i=NF;i>4;i-- ) {$i=$(i-1)}; $4=temp  ; print}'

This will preserve the final field, zip through all the fields and move each one backward to the fourth forward one, and then put the desired fourth field into place:

$ echo {1..10} | awk -v OFS="\t" '{temp=$NF; for( i=NF;i>4;i-- ) {$i=$(i-1)}; $4=temp  ; print}'
1   2   3   10  4   5   6   7   8   9
awk -v OFS="\t" '{ $4 = $NF; $NF=""; print }

To replace the fourth field with the last field:

awk -v OFS="\t" '{ $4 = $NF; $NF=""; print }

To insert the last field before the fourth field, we have to get a little creative:

awk -v OFS="\t" '{temp=$NF; for( i=NF;i>4;i-- ) {$i=$(i-1)}; $4=temp  ; print}'

This will preserve the final field, zip through all the fields and move each one backward to the fourth forward one, and then put the desired fourth field into place:

$ echo {1..10} | awk -v OFS="\t" '{temp=$NF; for( i=NF;i>4;i-- ) {$i=$(i-1)}; $4=temp  ; print}'
1   2   3   10  4   5   6   7   8   9
Source Link
DopeGhoti
  • 79.2k
  • 10
  • 107
  • 141

awk -v OFS="\t" '{ $4 = $NF; $NF=""; print }