i have a text file in which i want to put delimiters after certain characters ( fix),.
like put a delimiter (any like ,) after 1-3 character than 4 than 5 than 6-17 .....
$ cat temp.sh
string=2250300367391697204050470053888472012100817
for len in 17 5 4 3; do
string=`echo $string | sed "s/^\(.\{$len\}\)\(.*\)/\1,\2/"`
done
echo $string
$ ./temp.sh
225,0,3,003673916972,04050470053888472012100817
You can also do this with awk. Note that clist must be initialized to a list of the character positions after which a comma is added (in increasing numeric order):
your code works fine for me..Thanks :-)....( others codes are also working )
I have one more prob...actually this string was from a file , which contains n number of string (around 10K string )
this code works fine for 1 string ...but i need to work that in all my string ..(sample file given below)
while read string; do
for len in 17 5 4 3; do
string=`echo $string | sed "s/^\(.\{$len\}\)\(.*\)/\1,\2/"`
done
echo $string
# or the awk code
done < input.txt
To keep your code flexible, i.e. not restricted to a constant number of commas, and running sed just once on the entire file, you may want to try this:
$ POS="3 4 5 17 37 66"
$ for i in $POS
do sedcmd="s|.|&,|$i;"$sedcmd
done
$ echo $sedcmd
s|.|&,|66;s|.|&,|37;s|.|&,|17;s|.|&,|5;s|.|&,|4;s|.|&,|3;
$ sed $sedcmd file
019,0,3,003673916970,04050460090402182012,10081757059100402814136178910,00000918439013338
019,0,3,003673916971,04050300065520192012,10081736063534890419232404910,00000919033006189
225,0,3,003673916973,04050370172029692012,10081756033541310536336614910,00000918983673026
225,0,3,003673916972,04050470053888472012,10081756573580450426774801910,00000919046068826
You may even want to consider to use a variable token:
$ TOK=","
$ for i in $POS; do sedcmd="s|.|&$TOK|$i;"$sedcmd; done