Sed insert character at specific positions

sedtext formatting

I have hundreds of *.txt files which have a common format.

I can insert a comma at a specific position in one file, how can I generalize the below code to apply this operation at several places for all *.txtfiles in the directory?

sed -i 's/^\(.\{4\}\)/\1,/' blank.txt

For example inserting commas at positions 4, 8, 22 etc.

Something like this perhaps?

for i in *.txt; do
   sed -i 's/^\(.\{4\}\)/\1,/' $i
done

Best Answer

Start from the rightmost one:

sed -i 's/./&,/22;s/./&,/8;s/./&,/4' ./*.txt

Otherwise, the first substitution would affect the offset for the second. You can always account for it though:

sed -i 's/./&,/4;s/./&,/9;s/./&,/24' ./*.txt
Related Question