Reputation: 33
I have to replace blank spaces (" ") of all the values from an array in shell script. So, I need to make an array like this:
$ array[0]="one"
$ array[1]="two three"
$ array[2]="four five"
looks like this:
$ array[0]="one"
$ array[1]="two!three"
$ array[2]="four!five"
Replacing every blank space to another character with a loop or something, not changing value by value.
Upvotes: 3
Views: 3064
Reputation: 12356
$!/bin/sh
array=('one' 'two three' 'four five')
for i in "${!array[@]}"
do
array[$i]=${array[$i]/ /_}
done
echo ${array[@]}
Upvotes: 3
Reputation: 295403
array=('one' 'two three' 'four five') # initial assignment
array=( "${array[@]// /_}" ) # perform expansion on all array members at once
printf '%s\n' "${array[@]}" # print result
Upvotes: 6
Reputation: 369
Bash shell supports a find and replace via substitution for string manipulation operation. The syntax is as follows:
${varName//Pattern/Replacement}
Replace all matches of Pattern with Replacement.
x=" This is a test "
## replace all spaces with * ####
echo "${x// /*}"
You should now be able tp simply loop through the array and replace the spaces woth whatever you want.
Upvotes: 4