user3006685
user3006685

Reputation: 1

concatenate variable doesn't work how I want

I need to concatenate two variables and a character

The first variable $line is read from a file by line=$(awk "NR==$i" in_parameters.txt).

echo $line
2;0.250;0.250;1.520;0.000;0.025;32

The second variable is also read from a file

extr_out=$(awk "NR==1" "${i}_out.txt")

echo $extr_out
0.249510039979791

What I want is create line2= $line + ";" + $extr_out

echo $line2
2;0.250;0.250;1.520;0.000;0.025;32;0.249510039979791

I tried using

line2=$line
line2+=";"
echo $line2
;;0.250;0.250;1.520;0.000;0.025;32

or

line2=$line$extr_out
echo $line2
  0.2495100399797910;0.000;0.025;32

but the problem is that the value is written at the beginning of the chain and not appended at the end.

I probably do not understand something correctly. Can anybody help me with that? How does bash work with these variables?

Upvotes: 0

Views: 88

Answers (4)

John B
John B

Reputation: 3646

You can combine the variables, but the ; must be escaped as it would otherwise signify a new line in the script.

line2=$line\;$extr_out

Or you could use curly braces to separate the variable name from ; and use quotes.

line2="${line};$extr_out"

Upvotes: 0

BMW
BMW

Reputation: 45223

several ways

Using sed

echo "$(sed -n "${i}p" in_parameters.txt);$(head -1 ${i}_out.txt)"
echo "$(sed -n "${i}p" in_parameters.txt);$(sed -n "1p" ${i}_out.txt)"

Using awk

awk -v s=$i 'NR==FNR{if (FNR==s) printf $0 ";";next} {if (FNR==1) print}' in_parameters.txt ${i}_out.txt

Of course, you can use your exist code to merge them as @jaypal singh shows.

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77085

Concatenate like this?

$ line='2;0.250;0.250;1.520;0.000;0.025;32'
$ extr_out='0.249510039979791'
$ line2=$(echo "$line;$extr_out")
$ echo "$line2"
2;0.250;0.250;1.520;0.000;0.025;32;0.249510039979791

Upvotes: 1

rici
rici

Reputation: 241671

Your file in_parameters.txt has Windows line endings (CR-LF), so when you extract an entire line with awk, the line ends with a carriage return. Hence, when you append something to the end of the line, you are putting it after the carriage return, so it overwrites the text at the beginning of the line.

Use dos2unix to remove the CRs, and you should be fine. (You might want to check your other data files as well.)

Upvotes: 3

Related Questions