Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

1 Answer 1

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! –  CommuSoft 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.