我需要在shell脚本中替换数组中所有值的空格(“ ”)。因此,我需要创建以下形式的数组:
$ array[0]="one"
$ array[1]="two three"
$ array[2]="four five"
看起来像这样:
$ array[0]="one"
$ array[1]="two!three"
$ array[2]="four!five"
用循环或其他方式替换每个空格为另一个字符,而不是逐个更改值。
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 支持使用替换进行字符串操作。其语法如下:
${varName//Pattern/Replacement}
使用Replacement替换Pattern的所有匹配项。
x=" This is a test "
## replace all spaces with * ####
echo "${x// /*}"
现在,您应该能够简单地遍历数组并将空格替换为您想要的任何内容。
$!/bin/sh
array=('one' 'two three' 'four five')
for i in "${!array[@]}"
do
array[$i]=${array[$i]/ /_}
done
echo ${array[@]}
echo
是不幸的,特别是对于未引用的参数。printf '%q\n' "${array[@]}"
将更有效地演示数组元素之间的边界,因为echo
在视觉上不能区分带有空格的参数和两个单独的参数(而省略引号意味着本来应该是一个带有空格的参数在字符串拆分阶段被转换为多个参数)。 - Charles Duffy
array[0]=one
吗?也许是这样的吧。array[0] = one
不是一个赋值语句。 - Charles Duffy