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.

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

3
$ array=(01 02 03 10 20)
$ echo "${array[@]#0}"
1 2 3 10 20

Comments

2
shopt -s extglob
b=("${a[@]##+(0)}")
printf "%s\n" "${b[@]}"

1 Comment

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.
-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:

1 Comment

reposted, since the original in stackoverflow.com/a/26338759 was deleted due to somebody who posted the exact same question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.