Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

field ordering with sed

Tags:

bash

sed

I have a bash script with a sed command that I want to run on a csv file to change the order of some fields. This is what I tried:

sed -r '{
   s/(.*),(.*),(.*),(.*),(.*),(.*),(.*),(.*),(.*),(.*),(.*)/\1,\2,\3,\4,\5,\6,\8,\9,\10,\11,\7/
}' $1

The problem comes because I have 11 fields (i.e. two digit number) so when I specify the desired order i.e.

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

10 and 11 are taken as literals and this ruins my attempt. I have tried the obvious alternatives like:

"\1,\2,\3,\4,\5,\6,\8,\9,(10),(11),\7/"

or

"\1,\2,\3,\4,\5,\6,\8,\9,{10},{11},\7/"

or

"\1,\2,\3,\4,\5,\6,\8,\9,\(10),\(11),\7/"

or

"\1,\2,\3,\4,\5,\6,\8,\9,\{10},\{11},\7/"

But none of these work, they are also treated as literals. I am running out of imagination, do not know what else to try, any ideas?

I know there are other ways of going about this problem (like awk etc), but I would appreciate if your answers are focused in sed since the rest of my code is done using sed.

Wish to thank you all in advance!

like image 554
Miguel Garcia Avatar asked Nov 19 '25 12:11

Miguel Garcia


1 Answers

I see three blocks: fields 1-6, field 7 and the rest. So you can use

sed -r '{s/^(([^,]*,){6})([^,]*),(.*)/\1\4,\3/}'
like image 158
leu Avatar answered Nov 21 '25 05:11

leu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!