假设我将一些数据读入Bash数组:
$IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
现在,我想为数组中的每个元素打印第一个/ -sliced字段.
我所做的是遍历元素并使用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
格雷格的维基帮助了这里:
07000
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.06001