I have a list of numbers, for example








I am trying to prepend '0' to the four-digit numbers using sed, so the example above should give '01394' and '02350' and leave everything else as is.

The command I am using is sed 's/[0-9]\{4\}/0&/' but this includes numbers four digits and greater. I tried including end of line to indicate that I only want four digit numbers like so: sed 's/[0-9]\{4\}$/0&/' but this added a '0' to the second place of the five-digit numbers, so in the example above, '49020' would become '409020'.

Would appreciate any help on this!


You wish to prepend to only four-digit numbers, so you need to match beginning and ending, like this:

sed 's/^[0-9]\{4\}$/0&/'

I sometimes use something like this:

sed -r \
    -e 's/^[0-9]{1}$/0&/' \
    -e 's/^[0-9]{2}$/0&/' \
    -e 's/^[0-9]{3}$/0&/' \
    -e 's/^[0-9]{4}$/0&/' \
    -e 's/^[0-9]{5}$/0&/' \
    -e 's/^[0-9]{6}$/0&/'

which should leave all numbers as seven digits. There are of course easier ways with other tools than sed.


I find sed to be cranky. That sed lol here's how you do it. Instead of

 sed 's/[0-9]\{4\}/0&/'

Add in an end of string terminator:

 sed 's/^[0-9]\{4\}\>/0&/'

Note the /> after the second bracket. = End of word. It's stupid, don't know why specifying a len doesn't work. Maybe some experts can let us know why that is.

BTW tried with and without the string start caret - it works either way s/[0-9 or s/^[0-9]


This worked for me.

sed 's/^[0-9]\{4\}$/0&/'

I was able to modify it with the -i command and space /filename. Like below.

sed -i 's/^[0-9]\{4\}$/0&/' /tmp/filename

It would prepend the 4 digit numbers in the file with a 0.

I then changed it to do other funky changes that I required.

Thanks a mill for this one!!!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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