Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

Re: Replace leading zero with a space

 
SOLVED
Go to solution
Regular Advisor

Replace leading zero with a space

Here's a simple one but I'm having problems. I want to format a date, for example "11/01/2007" as "Nov 1" (I want to space out the leading zero). My script looks like this:

MON=`date +%b`
DAY=`date +%d`
HOUR=`date +%H`

EXT1=`echo ${MON} ${DAY} | tr "010203040506070809" " 1 2 3 4 5 6 7 8 9"`


This was working until today (Nov 20). Instead of getting "Nov 20", I get "Nov 2 ". I used the tr command to translate "Nov 01" to "Nov 1", etc. I use this script to extract data from the syslog.log which is in this format.
7 REPLIES 7
Honored Contributor

Re: Replace leading zero with a space

If you look at your tr statement, the 0203 part. 02 and 20 are then matched.

You will need to rework your matching.

Acclaimed Contributor
Solution

Re: Replace leading zero with a space


Use %e rather than %d for the day of the month.

Note that you should really do a single date command because you could execute this as 3 seprate commands and cross midnight so that you get a bogus date.

date '+%b %e %H' | read MON DAY HOUR
If it ain't broke, I can fix that.
Acclaimed Contributor

Re: Replace leading zero with a space

Hi Bob:

Simply use:

# DAY=`date +%e`

Regards!

...JRF...
Honored Contributor

Re: Replace leading zero with a space

If you don't want a leading zero or a space,
perhaps something like:

DAY=` date +%d | sed -e 's/^0//' `

or:

DAY=` date +%e | sed -e 's/^ //' `

"tr" looks like the wrong tool for this job.
Honored Contributor

Re: Replace leading zero with a space

If the only purpose of ${MON} and ${DAY} is to serve as temporary variables for ${EXT1}, you should forgo their use and set ${EXT1} directly from the 'date' command:

EXT1=$(date '+%b %e')

PCS
Acclaimed Contributor

Re: Replace leading zero with a space

Note that this trick out-bushwhacks two things at once AND makes sure that your date is self-consistent.

date '+%b %e %H' | read MON DAY HOUR

The '%e' outputs the day with a possible leading space but the read strips off the whitespace IFS (Input Field Separator) so that the day is left as "1" rather than " 1".
If it ain't broke, I can fix that.
Acclaimed Contributor

Re: Replace leading zero with a space

Any reason you want to do that?
To me it is better if all dates have the same number of character and don't special case any numbers. After all, you don't want to be like some European locales that actually have a space or remove it and be shorter.