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.

1 Answer 1


One way:

awk '/Chapter/{i=sprintf("%03d",i+1)}{print > "chap"i}' "$f.txt"
  • 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! Commented Dec 15, 2012 at 4:14
  • @CommuSoft : Updted now , this should be fine...
    – Guru
    Commented Dec 15, 2012 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
    Commented Dec 15, 2012 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" Commented Dec 15, 2012 at 18:08

You must log in to answer this question.

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