Please help - Command to Subtract two numbers without losing prefix zeros

Hello,

I have a variable LOGNUM with values 0000095, When i subtract the variable by 1, Its losing its leading zeros. Can you please help me here ?

LOGNUM=0000095
$OLDLOG=`echo "${LOGNUM}-1"|bc`
$ echo $OLDLOG
94

Am expecting output as

0000094

Appreciate your help!

Thanks,
Prince

LOGNUM=0000095
printf "%0${#LOGNUM}d\n" $(echo "$LOGNUM-1" | bc)
1 Like

Does it have to be bc ? Try

awk -vLNUM=$LOGNUM 'BEGIN {printf "%07d\n", LNUM-1}'
0000094
1 Like

When you post questions like this in the future, please tell us what operating system and shell you're using!

If you're using ksh , the easy way to do it is:

LOGNUM=0000095
OLDLOG=$(printf "%07d" $((LOGNUM - 1)))
echo $OLDLOG

If you're using bash , you could use:

LOGNUM=0000095
OLDLOG=$(printf "%07d" $(echo "$LOGNUM - 1" | bc))
echo $OLDLOG

You can't use arithmetic expansions for this with bash because bash treats all numbers with a leading 0 as octal (not decimal) values.

If you're using a pure Bourne shell, you could use:

LOGNUM=0000095
OLDLOG=`echo "$LOGNUM - 1" | bc`
OLDLOG=`printf "%07d" $OLDLOG`
echo $OLDLOG

One of the above is likely to work with any shell that is based on Bourne shell syntax. I make no claims about how to do this with a shell based on csh syntax.

1 Like

With bash , try

printf "%0${#LOGNUM}d\n" "$(( 10#$LOGNUM - 1 ))"
0000094
1 Like

Hello,

It works if number is below 0000099, If its above 0000100, it is not working as expected.

$ LOGNUM=0000120
$ printf "%0${#LOGNUM}d\n" "(( $LOGNUM - 1 ))"
0000079

Thanks,

See updated post #2 .

1 Like

Thanks, This works :slight_smile:

---------- Post updated at 01:35 AM ---------- Previous update was at 01:34 AM ----------

Thanks this works fine :slight_smile:

I doubt that it is working for all numbers below 99. And, you haven't told us what shell you're using to get these results. The above output is exactly what I would expect if you're using bash as your shell. As I explained in post #4 in this thread, bash treats 0120 (an octal number) as 80 (decimal).

1 Like

Thanks a lot. This works :slight_smile:

If you are in ksh (I don't think you ever said) you may be able to use typeset like this:-

typeset -Z7 LOGNUM
LOGNUM=95
((LOGNUM=$LOGNUM-1))
echo "$LOGNUM"

I get the output 0000094

I don't think this is available in bash, which is a little frustrating because it is so easy, however I'm sure there is a good reason. I have use this sort of thing frequently, so it would be know if there is a danger with it, hence why it has not made it into bash. If there is a neat way like this, I'd love to know it!

Kind regards,
Robin

Hi.

Also zsh , for a file z7:

zsh <<'EOF'
typeset -Z7 LOGNUM
LOGNUM=95
((LOGNUM=$LOGNUM-1))
echo "$LOGNUM"
EOF

producing:

$ ./z7
0000094

On a system like:

OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution        : Debian 8.8 (jessie) 
zsh 5.0.7

Best wishes ... cheers, drl