0

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?

1
  • Do you really want to replace newlines with spaces, or do you want each line to be a separate array element? Commented Oct 30, 2018 at 18:35

2 Answers 2

3

Use tr:

aws_user_roles+=("$(<<<"$aws_role_name" tr '\n' ' ')")
  • $(..) is command substitution
  • <<<"$variable" is a here-string
  • tr '\n' ' ' substitutes newlines for spaces.
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.