JAVIER COUCE LANGA JAVIER COUCE LANGA - 28 days ago 7
Bash Question

How can I format string in an array using shell script?

I'm beginner at shell scripting and I'm having a little troubles with my code.

My goal is to have control on the size and the format of the numbers in my array "mystring"

#!/bin/bash
mystring="333,4444,333,333,4444,333,333"
expectedValue=4
addLeftZero () {
if [ $myCount -eq $expectedValue ]
then
#the number has the correct size
else
#this is where I have to prepend "0" until the number has the expected lenght,
#for example the number "333" will be "0333"
fi
#here i have to return the full array with the mods
}
IFS=',' read -ra ADDR <<< "$mystring"
for i in "${ADDR[@]}"; do
myCount=${#i}
addLeftZero $i
return $i
done



0333,4444,0333,0333,4444,0333,0333


I have used
sed
command, but it seems like I need to edit it in a file, not directly in my code.

What command can I use to format my strings? Do am I using the function correctly? Do I have visibility of my variables? Do you know a
better way to reach my goal?

Thanks in advance!

Answer

Assuming that you just want to left-pad the numbers with zeroes, this can be done in a single command:

$ printf '%04d\n' "${ADDR[@]}"
0333
4444
0333
0333
4444
0333
0333

Here each number in your array is passed to printf as a separate argument - it takes care of the formatting for you.

Of course, whether this is suitable or not depends on how your plan on using these numbers.

As an aside, return is only for indicating whether a routine succeeded or not. As such, it only supports values from 0 to 255. To output something from a function or command, use standard output/error.