0

I am trying to read a text file which contains the following sample values:

Apple
Banana
Carrot

...I will then need write them to a variable as a single line delimited by comma.

var1=Apple,Banana,Carrot

How does one do it using bash script? Thank you in advance.

  • 2
    Does this answer your question? [Looping through the content of a file in Bash](https://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash) – alecxs Jan 20 '21 at 17:28
  • Reading the lines into a comma-delimited variable is a weird thing to want. Probably a better idea - depending on the use case, of course - is to read them into an array. – tripleee Jan 21 '21 at 05:22

1 Answers1

0

Using sed:

sed -rn 's/\n/;/g;s/^/var1=/p' file

Consume the file as one line (-z). Substitute every newline for ";" and then replace the start of the line with "var1="

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18