Shell parameter expansion on arrays

前端 未结 1 806
闹比i
闹比i 2020-12-11 12:55

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 f

相关标签:
1条回答
  • 2020-12-11 13:19

    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\n" "${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
    
    0 讨论(0)
提交回复
热议问题