Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have this:

date +"%H hours and %M minutes"

I use festival to say it up.. but it says like: "zero nine hours".. I want it to say "nine hours"!

but date always give me 09... so I wonder if bash can easly make that become just 9?

in the complex script I tried like

printf %d 09

but it fails.. not octal :(

any idea?

share|improve this question
add comment

3 Answers

up vote 9 down vote accepted
  • In your case, you can simply disable zero padding by append - after % in the format string of date: %-H

    By default, date pads numeric fields with zeroes. The following optional flags may follow '%':

    • - (hyphen) do not pad the field
    • _ (underscore) pad with spaces
    • 0 (zero) pad with zeros
    • ^ use upper case if possible
    • # use opposite case if possible

    See date manual

  • If you want to interpret number in different base, in bash

    • Constants with a leading 0 are interpreted as octal numbers.
    • A leading 0x or 0X denotes hexadecimal.
    • Otherwise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base

    So, to interpret a number as decimal, use 10#n form, eg. 10#09

    echo $((10#09*2))
    18
    

    See Arithmetic Evaluation section of bash manual.

share|improve this answer
    
Good one .......... –  Rahul Patil Apr 3 '13 at 3:56
    
thx, very detailed! btw, echo $((011)) $((10#011)) is another good example that outputs 9 11 –  Aquarius Power Apr 29 '13 at 21:10
add comment

In general in bash:

test ${#number} -eq 2 && number=${number#0}

resulting in

date +"%H %M" | 
{ read hours minutes
hours=${hours#0}
minutes=${minutes#0}
echo "${hours} hours and ${minutes} minutes"; }

Or, different:

date +"%H hours and %M minutes" | sed -n -e 's/0\([0-9]\)/\1/g' -e p

I am surprised that date does not have appropriate format options.

share|improve this answer
add comment

Portably, you can easily remove a leading 0 from a variable. This leaves the variable unchanged if there is no leading 0.

eval $(date +"h=%H m=%M")
h=${h#0}
m=${m#0}
say "$h hours and $m minutes"

In bash, ksh or zsh, you can use ksh's additional glob patterns to remove any number of leading 0s. In bash, run shopt -s kshglob first. In zsh, run setopt ksh_glob first.

eval $(date +"h=%H m=%M")
h=${h#+(0)}
m=${m#+(0)}
say "$h hours and $m minutes"
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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