简体   繁体   中英

Replace blank spaces in an array in bash

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.

array=('one' 'two three' 'four five') # initial assignment
array=( "${array[@]// /_}" )          # perform expansion on all array members at once
printf '%s\n' "${array[@]}"           # print result

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.

$!/bin/sh

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

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

echo ${array[@]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM