rebutia
rebutia

Reputation: 15

Combine strings contained in variables delimited by a new line

I have three variables in Bash, all of them containing strings delimited by a new line, e.g.:

Variable A:

one
two
three

Variable B:

Mon
Tue
Wed

Variable C:

10
11
12

The three variables always hold the exact same number of elements delimited by a new line.

My goal is to take a line (starting from the first one) from variable A, add some text in between, then take a line from variable B, add some text in between again, and finally, take a line from variable C and add some text at the end. Then, i want to append the result of this to a final variable, let's say $final, that after the loop is over (i.e., we have walked through all the lines), should look like this:

one - Mon [10]; two - Tue [11]; three - Wed [12]

Is awk capable of that or i should use other tools?

Upvotes: 0

Views: 60

Answers (2)

tshiono
tshiono

Reputation: 22012

Would you please try the following:

# assign the variables
variableA="one
two
three"

variableB="Mon
Tue
Wed"

variableC="10
11
12"

# transform the variables to arrays
readarray -t aryA <<< "$variableA"
readarray -t aryB <<< "$variableB"
readarray -t aryC <<< "$variableC"

# construct the variable $final
for ((i=0; i<3; i++)); do
    final+="${aryA[$i]} - ${aryB[$i]} [${aryC[$i]}]; "
done

# remove trailing semicolon and whitespace
final="${final%;*}"

echo "$final"

Output:

one - Mon [10]; two - Tue [11]; three - Wed [12]

[Explanation]

  • readarray (or mapfile) reads standard input line by line and puts each line in an array element.
  • That is, if variableA which contains the three lines is fed to readarray, then the array aryA is created containing aryA[0]=one, aryA[1]=two, and so on.
  • Then the variable final is created by appending the elements of the arrays.

Hope this helps.

Upvotes: 2

William Pursell
William Pursell

Reputation: 212208

I think I would go with:

paste <(echo "$A") <(echo "$B") <(echo "$C") \
| awk '{printf "%s - %s [%s]; ", $1, $2, $3}'

Upvotes: 3

Related Questions