Shell 数组的参数扩展
Shell parameter expansion on arrays
假设我将一些数据读入 Bash 数组:
$ IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
现在,我想为数组中的每个元素打印第一个 /
切片字段。
我所做的是遍历元素并使用 shell 参数扩展从第一个 /
:
中删除所有内容
$ for w in "${arr[@]}"; do echo "${w%%/*}"; done
hello
are
iam
但是,由于 printf
允许我们在单个表达式中打印数组的全部内容:
$ printf "%s\n" "${arr[@]}"
hello/how
are/you
iam/fine
...我想知道有没有办法在使用printf
时使用shell参数扩展${w%%/*}
,而不是循环遍历所有元素并做它反对每一个。
哦,我刚刚找到方法:正常使用参数扩展,只针对 ${arr[@]}
而不是 ${arr}
!
$ IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
$ printf "%s\n" "${arr[@]%%/*}"
hello
are
iam
Greg 的 wiki 在这里提供了帮助:
BASH arrays are remarkably flexible, because they are well integrated
with the other shell expansions. Any parameter expansion that can be
carried out on a scalar or individual array element can equally apply
to an entire array or the set of positional parameters such that all
members are expanded at once, possibly with an additional operation
mapped across each element.
$ a=(alpha beta gamma) # assign to our base array via compound assignment
$ echo "${a[@]#a}" # chop 'a' from the beginning of every member
lpha beta gamma
$ echo "${a[@]%a}" # from the end
alph bet gamm
$ echo "${a[@]//a/f}" # substitution
flphf betf gfmmf
基于@fedorqui 的回答,如果 OP 想要输出数组而不是字符串,这对我有用-
a=(alpha beta gamma)
newArr=( "${a[@]//a/f}" )
P.S。我个人到达这个 post 寻找在对数组的每个元素进行替换后输出一个数组。
假设我将一些数据读入 Bash 数组:
$ IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
现在,我想为数组中的每个元素打印第一个 /
切片字段。
我所做的是遍历元素并使用 shell 参数扩展从第一个 /
:
$ for w in "${arr[@]}"; do echo "${w%%/*}"; done
hello
are
iam
但是,由于 printf
允许我们在单个表达式中打印数组的全部内容:
$ printf "%s\n" "${arr[@]}"
hello/how
are/you
iam/fine
...我想知道有没有办法在使用printf
时使用shell参数扩展${w%%/*}
,而不是循环遍历所有元素并做它反对每一个。
哦,我刚刚找到方法:正常使用参数扩展,只针对 ${arr[@]}
而不是 ${arr}
!
$ IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
$ printf "%s\n" "${arr[@]%%/*}"
hello
are
iam
Greg 的 wiki 在这里提供了帮助:
BASH arrays are remarkably flexible, because they are well integrated with the other shell expansions. Any parameter expansion that can be carried out on a scalar or individual array element can equally apply to an entire array or the set of positional parameters such that all members are expanded at once, possibly with an additional operation mapped across each element.
$ a=(alpha beta gamma) # assign to our base array via compound assignment $ echo "${a[@]#a}" # chop 'a' from the beginning of every member lpha beta gamma $ echo "${a[@]%a}" # from the end alph bet gamm $ echo "${a[@]//a/f}" # substitution flphf betf gfmmf
基于@fedorqui 的回答,如果 OP 想要输出数组而不是字符串,这对我有用-
a=(alpha beta gamma)
newArr=( "${a[@]//a/f}" )
P.S。我个人到达这个 post 寻找在对数组的每个元素进行替换后输出一个数组。