2

I have a lot of lines like below:

123;XXXXXXXXXXXXXXX;ABCDE;YYYYYYYY;08082010;000000000000000;03/08/10;110000;ZZZZZZZZZZZZZZZZZ;0002

I just want to change the number format (15 digit) XXXXXXXXXXXXXXX to XXXXXXXXX;XXX;XXX

and

YYYYYYYYY (9 digit) to YYYYYY;YYY

with sed.

any other format just leave the default

2 Answers 2

1

Assuming that "X" and "Y" represent digits and that your example line actually has 9 "Y" digits (it has eight in your question, but the split you want shows 9), this should work:

sed 's/;\([0-9]\{6\}\)\([0-9]\{3\}\);/;\1;\2;/;s/;\([0-9]\{9\}\)\([0-9]\{3\}\)\([0-9]\{3\}\);/;\1;\2;\3;/'

You could use variables to make it perhaps a little more readable:

dig3="[0-9]\{3\}"
dig6="[0-9]\{6\}"
dig9="[0-9]\{9\}"
sed "s/;\($dig6\)\($dig3\);/;\1;\2;/;s/;\($dig9\)\($dig3\)\($dig3\);/;\1;\2;\3;/"
1

when you have structured data and field delimiters, its easier to use awk. In your data, you have ";" as delimiters, so use it.

awk -F";" '
{
  $2=substr($2,0,9)";"substr($2,9,3)";"substr($2,12,3)
  $4=substr($4,0,6)";"substr($4,7)
}{print}
' OFS=";" file

The awk statement says use ";" as delimiters, then work on field 2 and 4 ($2, $4) for your desired output. To change the format, use substringing. Finally set the output field separator back to ";".

this is clearer than using long cluttered regex with sed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .