加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

数组上的Shell参数扩展

发布时间:2020-12-15 19:01:06 所属栏目:安全 来源:网络整理
导读:假设我将一些数据读入Bash数组: $IFS=" " read -a arr "hello/how are/you iam/fine/yeah" 现在,我想为数组中的每个元素打印第一个/ -sliced字段. 我所做的是遍历元素并使用shell参数扩展来从第一个/中删除所有内容: $for w in "${arr[@]}"; do echo "${w%
假设我将一些数据读入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 "%sn" "${arr[@]}"
hello/how
are/you
iam/fine

…我想知道在使用printf时是否有办法使用shell参数扩展${w %% / *},而不是循环遍历所有元素并对每一个元素进行操作.

哦,我刚刚找到了方法:正常使用参数扩展,只针对${arr [@]}而不是${arr}!
$IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
$printf "%sn" "${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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读