Yugal Jindle Yugal Jindle - 4 years ago 417
Bash Question

Bash : How to concatenate all lines from a file?

I have a file

csv
:

data1,data2,data2
data3,data4,data5
data6,data7,data8


I want to convert it to (Contained in a variable):

variable
=
data1,data2,data2%0D%0Adata3,data4,data5%0D%0Adata6,data7,data8


My attempt :

data=''
cat csv | while read line
do
data="${data}%0D%0A${line}"
done
echo $data # Fails, since data remains empty (loop emulates a sub-shell and looses data)


Please help..

Answer Source

In bash,

data=$(
while read line
do
  echo -n "%0D%0A${line}"
done < csv)

In non-bash shells, you can use `...` instead of $(...). Also, echo -n, which suppresses the newline, is unfortunately not completely portable, but again this will work in bash.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download