Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

bash - Shell parameter expansion on arrays

Say I read some data into a Bash array:

$ IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"

Now, I want to print the first /-sliced field for each element in the array.

What I do is to loop over the elements and use shell parameter expansion to strip everything from the first /:

$ for w in "${arr[@]}"; do echo "${w%%/*}"; done
hello
are
iam

However, since printf allows us to print the whole content of the array in a single expression:

$ printf "%s
" "${arr[@]}"
hello/how
are/you
iam/fine

... I wonder if there is a way to use the shell parameter expansion ${w%%/*} at the time of using printf, instead of looping over all the elements and doing it against every single one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Oh, I just found the way: just use the parameter expansion normally, only that against ${arr[@]} instead of ${arr}!

$ IFS=" " read -a arr <<< "hello/how are/you iam/fine/yeah"
$ printf "%s
" "${arr[@]%%/*}"
hello
are
iam

Greg's wiki helped here:

Parameter Expansion on Arrays

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...