Extending shell parameters on arrays

Let's say I read some data in 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 of the array.

What I do is iterate over the elements and use the shell parameter extension to remove everything from the first / :

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

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

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

... I wonder if there is a way to use the shell parameter extension ${w%%/*} while using printf instead of iterating over all the elements and doing it against each individual.

0
source share
1 answer

Oh, I just found a way: just use the parameter extension normally, only for ${arr[@]} instead of ${arr} !

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

Greg wiki helped here:

Extending parameters in arrays

BASH arrays are extremely flexible as they integrate well with other shell extensions. Any extension of a parameter that can be performed on a scalar or a separate element of the array can equally be applied to the whole array or set of positional parameters, so that all members are expanded immediately, possibly with an additional operation associated with 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 
+1
source

Source: https://habr.com/ru/post/1263442/


All Articles