swam
swam

Reputation: 303

Bash script "concatenate" multi-lined variables

In a bash script I have three variables that contain multiple lines of equal length.

For example:

$a 
one
two
three

$b
dog
cow
fish

$c
blue
red
green

In what way could I echo the output to a similar format:

onedogblue
twocowred
threefishgreen

I tried a for loop of looping through each variable and echoing each line, but was not getting the desired result. Any advice?

EDITING FOR MORE ACCURACY So my script will be run with a text file as an argument (./script.sh textfile) I have three variables with similar content to this variable:

#!/bin/sh
x=`awk 'NR>1{print $1}' $1 | tr '[:upper:]' '[:lower:]'`

I am manipulating the same text file from the command argument to get different parts of the file. Ultimately want to "paste" them together in this format "$x" : "$y""$z. I know there are probably more sensible ways to process the text file into the format desired, but I would like to find if there is such a way to format it in the way listed above.

Upvotes: 3

Views: 3519

Answers (2)

Jose Martinez
Jose Martinez

Reputation: 11992

How about not having the quotes in the echo so that the newlines are removed then use sed to remove the white spaces.

$a="one
> two
> three"
$
$echo "$a"
one
two
three
$
$echo $a
one two three
$
$echo $a | sed 's/ //g'
onetwothree
$

Upvotes: 0

fedorqui
fedorqui

Reputation: 289505

paste is your friend:

$ paste -d' ' <(echo "$a") <(echo "$b") <(echo "$c")
one dog blue
two cow red
three fish green

Noting that $a is got through a=$(cat a), with the file a containing the lines your provided. The same applies to $b and $c. Also, it is important to see that I am doing echo "$a", with quotes around the variable, so that the format is kept. Otherwise, the new lines wouldn't appear.

paste does not allow -d'' (that is, empty delimiter), so if you want to remove the spaces you can pipe to for example tr:

$ paste -d' ' <(echo "$a") <(echo "$b") <(echo "$c") | tr -d ' '
onedogblue
twocowred
threefishgreen

Upvotes: 8

Related Questions