0

I am taking an input of elements from the user and displaying it in a file. However, I need to do one more task. I need to replace the first character of each array element with a dot(.) which is unfortunately not working for me.

Please find my code below:

while read line
do
    my_array=("${my_array[@]}" $line)
done

echo ${my_array[@]/my_array[@][0]/.}

Any help would be highly appreciated, thanks.

2 Answers 2

4

With GNU bash:

my_array=(foo bar abc)
echo "${my_array[@]/?/.}"

Output:

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

Comments

1

You don't need to populate the array first and do the post processing later. While populating array itself you can do this:

my_array=()

while read -r line; do
    my_array+=( ".${line:1}" )
done
  • ".${line:1}" will place DOT at first place followed by substring of $line from next position onwards.
  • Also note right way of populating an array in a loop by using my_array+=( ".${line:1}" )

Comments

Your Answer

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