anita
anita

Reputation: 177

How to cat multi-line bash variables?

When I try to save columns of bash variables and then try to cat them together, I get an error.

These are the variables:

$ a_var=$(grep -i "word" {input} | awk '{print $3}')

$ echo $a_var
hello1
hello2
hello3

$ b_var=$(grep -i "otherword" {input} | awk '{print $3}')

$ echo $b_var
hello10
hello11
hello12

But then when I try:

$ new_var=$(cat $a $b)

I get some weird output that can't save to a file or a new variable.

cat: hello1: No such file or directory
cat: hello2: No such file or directory
cat: hello3: No such file or directory
cat: hello10: No such file or directory
cat: hello11: No such file or directory
cat: hello12: No such file or directory

$ echo $new_var

$

(When I "echo" there is a blank return.)

What is going on? How can I concatenate my bash variables together?

Edit: I want the output to look like this (I want to save this column of values to a file):

hello1
hello2
hello3
hello10
hello11
hello12

Upvotes: 2

Views: 1381

Answers (2)

user14642966
user14642966

Reputation:

This is how you concatenate these string variables in shell:

c_var="$a_var$b_var" ; echo $c_var

Or generally: c="$a$b" ; echo $c

Upvotes: 2

zhaoyanggh
zhaoyanggh

Reputation: 285

Although cat in Linux stands for concatenate, it not going to act on variables. Actually, it is used to connect files and print to the standard output device. For your case, use c_var="${a_var}${b_var}"

Upvotes: 6

Related Questions