Reputation: 1325
I'm assigning values to an array inside a for loop:
aws_user_roles+=("$aws_role_name")
If I were assigning the values of the array from a command and want to strip the newline I could go:
readarray -t aws_roles < <(...some aws commands...)
My for loop looks something like this:
for ((has_role_index=0;has_role_index<${#aws_user_has_roles[@]};++has_role_index)); do
aws_user_roles+=("$aws_role_name")
declare -p aws_user_roles
done
How can I strip out the newline from the array elements in aws_user_roles
and replace it with a space?
Upvotes: 0
Views: 1445
Reputation: 50750
Use pattern substitution:
aws_user_roles+=("${aws_role_name//$'\n'/ }")
From man bash
:
${parameter/pattern/string}
Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced
Upvotes: 1
Reputation: 140990
Use tr
:
aws_user_roles+=("$(<<<"$aws_role_name" tr '\n' ' ')")
$(..)
is command substitution<<<"$variable"
is a here-stringtr '\n' ' '
substitutes newlines for spaces.Upvotes: 3