Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a file like this:


I want to zero-pad the middle field to give the result:


How do I make a script that woud do this?

I've seen an example like this

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

but I don't really understand it and thus can't get it working.

share|improve this question
up vote 6 down vote accepted

Try this:

awk -F , '{ printf "%i,%08i,%s\n" , $1 , $2 , $3 }' file
share|improve this answer
will do , thanks, can you explain how this works? – mattm123 Oct 25 '10 at 14:58
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

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


  • 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

share|improve this answer

You must log in to answer this question.

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