Trying to find how to replace a leading zero with white space in SED. Attempting to get day of month and replace with space to filter some data that I am screen scraping.

The code I have is as follows:

DoM=$(date --date="-1 day" +"%d")
DoMSp=$(echo $DoM | sed "s/^0*/\ /g"); echo $DoMSp

But the problem is when I have a day from 1-9 instead of printing " 1" it prints "1", no matter how many "\ " I try to put in the expression.

$ DoMSp=$(echo $DoM | sed "s/^0*/\ /g"); echo $DoMSp

$ DoMSp=$(echo $DoM | sed "s/^0*/\ \ \ \ \ \ /g"); echo $DoMSp
  • Quote your expansion on the echo, otherwise it strips whitespace.
    – jordanm
    Jun 2, 2014 at 16:31
  • This might just be your example, but what about using date --date "-1 day" +"%_d" or date --date "-1 day" +"%e". Those make date return a space-padded field.
    – derobert
    Jun 2, 2014 at 16:55

1 Answer 1


You don't have to escape space in sed command, just use double quote in echo command to avoid word splitting:

$ DoMSp=$(echo "$DoM" | sed "s/^0*/ /"); echo "$DoMSp"
  • @GautamSomani: The pattern only match at start of line, so it's not a problem. But it is still not necessary to use g here, removed it!
    – cuonglm
    Jun 3, 2014 at 5:08
  • Yup. Agreed. Will delete my comment. Jun 3, 2014 at 5:09

You must log in to answer this question.

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