i have a file like this

123123213,456,be
124243233,4346,ytr
123123123,436535,uytr
324234324,322,yt
234324323,32,tyutr

and want to zero pad the middle field to give the result

123123213,00000456,be
124243233,00004346,ytr
123123123,00436535,uytr
324234324,00000322,yt
234324323,00000032,tyutr

can anyone think of ascript that woudl do this

I've seen an example like this

awk '{ $6=sprintf("%06s", $6); print $0}'

but i dont really understand it so cant get it working

link|improve this question

75% accept rate
feedback

2 Answers

up vote 3 down vote accepted

Try this:

awk -F , '{ printf "%i,%08i,%s\n" , $1 , $2 , $3 }' file
link|improve this answer
will do , thanks, can you explain how this works? – mattm123 Oct 25 '10 at 14:58
2  
Ok, -F , tells awk to use , as field separator, then it prints all the three fields ($1, $2 and $3) with a custom format: "%i,%08i,%s\n", %i is for integers, %08i sets the field width to 8 left-padding with zeros and is %s for strings. For more info see man printf or here. Hope this helps you. – cYrus Oct 25 '10 at 15:14
thanks a lot :) – mattm123 Oct 25 '10 at 16:32
i need to change the comma seperator into a cedilla using the unput $'\xE7' but when i use printf "%i "$'\xE7'" %08i\n" , $1, $2 it doesnt come out correct. any ideas? – mattm123 Oct 26 '10 at 13:35
Something like: awk -F , '{ printf "%i\xe7%08i\xe7%s\n" , $1 , $2 , $3 }' file? – cYrus Oct 26 '10 at 14:02
feedback

Since you tagged your question [sed], here is a sed version based on the script here.

sed 's/[^,][^,]*/\n0000000&/2;s/\n[^,]*\(.\{8\}\),/\1,/' inputfile

Explanation:

  • a field consists of a group of one or more non-commas: [^,][^,]* (this could also be written as [^,]\+)
  • substitute for the second field (match) (s///2) a newline, a bunch of zeros and the contents of the match: \n0000000& (the newline is used to mark the beginning of the field for the next step)
  • now match the newline, zero or more non-commas and exactly eight \{8\} of any character (capturing those characters \(\) ) followed by a comma
  • substitute the captured characters \1 for the match, this removes the temporary newline and the excess zeros

The way this works is to add excess zeros at the beginning of the field then chop off all but the

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.