Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. 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 book in text format. I would like to split the book into several files where each file contains a single chapter. Therefore I'm using the following command:

awk '/Chapter/{i++}{print > "chap"i}' "$f.txt"

where $f is just the variable in a for-loop. I notice however that the files are named:


Is their a way to add leading zeros? So the files are named:


I'm using /bin/sh as default shell.

share|improve this question
up vote 4 down vote accepted

One way:

awk '/Chapter/{i=sprintf("%03d",i+1)}{print > "chap"i}' "$f.txt"
share|improve this answer
Yeah. This sure works, but I think you will agree this is not very elegant. I'm looking for a solution where one can simply add more zeros,... But it works! – Willem Van Onsem Dec 15 '12 at 4:14
@CommuSoft : Updted now , this should be fine... – Guru Dec 15 '12 at 4:30
Or, a minor variation with which you can pass the width as an arg to awk: awk -v"w=3" '/Chapter/{print > "chap"sprintf("%0"w"d",++i)}' – Peter.O Dec 15 '12 at 14:58
@Peter.O, more elegant to write sprintf("%0*d", w, ++i) -- "A * in place of either the width or prec specifications causes their values to be taken from the argument list" – glenn jackman Dec 15 '12 at 18:08

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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