2

I need to strip the first 0 from all values in an array, e.g. change

array=( 01 02 03 [...] 10 [...] 20 [...] )

to

array=(1 2 3 [...] 10 [...] 20 [...] )  

I think I can do this with ${parameter/pattern/string} but I am quite lost with the syntax.

Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
kesm0
  • 847
  • 1
  • 11
  • 20

4 Answers4

4

Given that it's an array of numbers, I'd do it arithmetically instead of attempting to perform string replacement:

$ a=( {01..20} )
$ echo "${a[@]}"
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20
$ b=()
$ for i in "${a[@]}"; do b+=( $((10#$i)) ); done
$ echo "${b[@]}"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Here $((10#$i)) would cause the variable i to be evaluated as a base-10 number.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
devnull
  • 118,548
  • 33
  • 236
  • 227
3
$ array=(01 02 03 10 20)
$ echo "${array[@]#0}"
1 2 3 10 20
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
2
shopt -s extglob
b=("${a[@]##+(0)}")
printf "%s\n" "${b[@]}"
iruvar
  • 22,736
  • 7
  • 53
  • 82
  • This will strip all leading zeroes, OP asked only for the first in which case `extglob` is not needed. Though @devnull's solution is probably the sanest. – Adrian Frühwirth Apr 22 '14 at 14:09
-1

You can use parameter expansion and redefine the array directly:

array=(${array[@]#0})

${string#substring} strips the shortest match of $substring from front of $string.

If you want to strip multiple zeroes, e.g. (001 002) to (1 2), you can use shopt -s extglob and then "${var##*(0)}".

Test

$ a=(01 02 03 10 11)
$ ar=(${a[@]#0})
$ for i in "${ar[@]}"; do echo $i; done
1
2
3
10
11

And with multiple zeroes:

$ a=(01 11 0003)
$ ar=(${a[@]#0})
$ for i in "${ar[@]}"; do echo ${i##*(0)}; done
1
11
003
$ shopt -s extglob
$ for i in "${ar[@]}"; do echo ${i##*(0)}; done
1
11
3

Sources:

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • reposted, since the original in http://stackoverflow.com/a/26338759/ was deleted due to somebody who posted the exact same question. – fedorqui May 28 '15 at 10:34