3

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.

1
  • You mean array[0]=one, maybe? array[0] = one isn't an assignment. Commented May 18, 2015 at 3:22

3 Answers 3

6
array=('one' 'two three' 'four five') # initial assignment
array=( "${array[@]// /_}" )          # perform expansion on all array members at once
printf '%s\n' "${array[@]}"           # print result
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3
$!/bin/sh

array=('one' 'two three' 'four five')

for i in "${!array[@]}"
do 
    array[$i]=${array[$i]/ /_}
done

echo ${array[@]}

2 Comments

Much better now, though the use of echo is unfortunate, especially with unquoted arguments. printf '%q\n' "${array[@]}" would be a more effective demonstration of where the boundaries between array elements are, since echo doesn't visually distinguish between an argument with a space and two separate arguments (and leaving out your quotes means that something that would otherwise have been one argument with a space gets transformed into multiple arguments during string-splitting phase).
One last issue here -- the /bin/sh shebang doesn't guarantee a shell with arrays will be used to run this script.

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.