Ad

How To Create A String Of Filenames Separated By Comma In Shell Script?

- 1 answer

I am trying to create a string eg (file1.txt,file2.txt,file3.txt). All these 3 files names are within a file.

ls file*.txt > lstfiles.txt

while read filename; do
  filename+=$line","
done <lstfiles.txt

This returns me with output:

file1.txt,file2.txt,file3.txt,

How can I find the last iteration of the loop so I dont add another comma at the end.

Required output:

file1.txt,file2.txt,file3.txt
Ad

Answer

For your use case I would rather get rid of the while loop and combine sedand tr commands like so:

sed -e '$ ! s/$/,/g' lstfiles.txt | tr -d '\n'

Where sed command replace each line endings execept the last one with a comma and tr command remove the linebreaks.

Ad
source: stackoverflow.com
Ad