Remove leading zero from BASH array variables

I am trying to remove leading zeros 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 would like to remove the leading zeros from the dates and save back to an array or another array so that I can repeat the iteration at 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 with running several BASH scripts)

+4
source share
4 answers

Use parameter extension:

 DATES=( ${DATES[@]#0} ) 
+12
source

Using bash arithmetic, you can avoid octal problems by indicating that your numbers are 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 
+4
source

You can use the bash parameter extension (see http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html ) as follows:

 echo ${DATESLZ[@]#0} 
+1
source

If: ${onedate%%[!0]*} selects all 0 before the line $onedate .

we could remove these zeros by doing this (portable):

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

In your case (bash only):

 #!/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 

It will be printed:

 $ script.sh 01 1 02 2 02 2 08 8 10 10 18 18 20 20 21 21 0008 8 00101 101 
0
source

Source: https://habr.com/ru/post/1484634/


All Articles