Home > Net >  Update nth element in delimited line [unix scripting]
Update nth element in delimited line [unix scripting]

Time:11-09

i have a .temp file that contains comma-delimited lines:

abc,1,000,aaa,zzz,2,234,OOO,00001,01,123,214
def,2,003,bbb,yyy,4,345,PPP,00002,02,133,224
ghi,3,011,ccc,xxx,6,456,QQQ,00003,03,143,234
jkl,4,012,ddd,www,8,567,RRR,00004,04,153,244
...

each line is read and 3rd column is used to update 9th column

i'm able to do this using:

indexToUpdate=9

updatedLine="$(echo "$line" | sed "s/[^,]*/$new9thColumnData/$indexToUpdate")"

my question is, is there a faster way to update 9th column data aside from using sed?

CodePudding user response:

In addition to potong's suggestion, you could use e.g. awk:

awk -F ',' '{ OFS=FS; $9=$3; print }' file

CodePudding user response:

perl -lanF, -e 'print join ",", @F[0..7,2,9..$#F]' file

or, like awk above:

perl -lanF, -e '$F[8]=$F[2]; print join ",", @F' file

Uses perl's autosplit to split on commas, which creates the @F array, which is then printed in a different order.

Not that perl is faster than either sed or awk...

  • Related