4

I am trying to remove leading zeroes from a BASH array... I have an array like:

echo "${DATES[@]}"

returns

01 02 02 03 04 07 08 09 10 11 13 14 15 16 17 18 20 21 22 23

I'd like to remove the leading zeroes from the dates and store back into array or another array, so i can iterate in another step... Any suggestions?

I tried this,

for i in "${!DATES[@]}"
do
    DATESLZ["$i"]=(echo "{DATES["$i"]}"| sed 's/0*//' ) 
done

but failed (sorry, i'm an old Java programmer who was tasked to do some BASH scripts)

4

4 回答 4

12

使用参数扩展:

DATES=( ${DATES[@]#0} )
于 2013-06-05T12:40:58.803 回答
4

使用 bash 算术,您可以通过指定数字为 base-10 来避免八进制问题:

day=08
((day++))           # bash: ((: 08: value too great for base (error token is "08")
((day = 10#$day + 1))
echo $day              # 9
printf "%02d\n" $day   # 09
于 2013-06-05T12:46:57.313 回答
1

您可以像这样使用 bash 参数扩展(参见http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html):

echo ${DATESLZ[@]#0}
于 2013-06-05T12:41:49.657 回答
0

If:${onedate%%[!0]*}将选择字符串前面的所有 0 $onedate

我们可以通过这样做来删除那些零(它是可移植的):

echo "${onedate#"${onedate%%[!0]*}"}"

对于您的情况(仅 bash):

#!/bin/bash
dates=( 01 02 02 08 10 18 20 21 0008 00101 )

for onedate in "${dates[@]}"; do
    echo -ne "${onedate}\t"
    echo "${onedate#"${onedate%%[!0]*}"}"
done

将打印:

$ script.sh
01      1
02      2
02      2
08      8
10      10
18      18
20      20
21      21
0008    8
00101   101
于 2015-09-08T15:38:50.923 回答