Using sed to prepend zero to four-digit numbers

sed

I have a list of numbers, for example

1394

49020

344

34

4904290

2350

5

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!

Best Answer

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.

Related Topic