Home > Software engineering >  How to create a string of filenames separated by comma in shell script?
How to create a string of filenames separated by comma in shell script?

Time:02-18

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

CodePudding user response:

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.

CodePudding user response:

Probably avoid using ls in scripts though.

printf '%s,' file*.txt |
sed 's/,$/\n/'

assuming your sed recognizes \n to be a newline, and copes with input which doesn't have a final newline.

  • Related