Rearranging columns using awk

The -F option needs an argument (field separator): -F, for example.

The end of the awk script must be separated with a (space char) with the rest of the parameters.

If the field separator is , and you wish to keep it, and if the number of column is constant and lower than or equal to 11, give a try to this:

awk -F, '{print $1,$2,$3,$4,$5,$6,$8,$9,$10,$11,$7}' OFS=, "$file"

If your field separator is a semicolon don't forget to set it in quotes like so

awk -f';' '{print $1,$2,$3,$4,$5,$6,$8,$9,$10,$11,$7}' OFS=';' "$file"

Shorter solution would be

awk -F',+' -v OFS=, '{$(NF+1)=$7; $7=""; $0=$0; $1=$1}1' file

I'm not sure if ,+ will work in all awk versions, but works at least in GNU awk, also with -compatibility mode.

Explanation:

  • $(NF+1)=$7: first we add 7th field to the end of the line (could be $12=$7 in this case)
  • $7="": in next step 7th field is erased (but surrounding delimiters stay)
  • to remove delimiters we need to re-set whole record (via $0=$0) treating multiple commas as field separator (this is done via -F',+', here + means one or more times), and also rearrange current record via $1=$1 to force rebuilding the line using previously set output field separator (set by an option -v OFS=,)
  • after all shuffling is done we are ready to print the result with 1

Example input:

1,2,3,4,5,6,7,8,9,10,11

output

1,2,3,4,5,6,8,9,10,11,7

If you're printing with OFS=, so with no separator between the fields, you can simply save the value of $7 in a variable, set $7 to empty and print the line and the variable directly. You don't need to specify all the fields:

$ cat file
1,2,3,4,5,6,7,8
$ awk -F, -vOFS= '{k=$7; $7=""; print $0,k}' file 
12345687