I am trying to create different files in a single directory using a file that contains the file names. For example if the file contains


it will create two files file1.md and file2.md in the directory.

I am using the command touch {$(cat file)}.md but this creates a single file file1,file2.md


You could replace the commas with newlines using tr and read the result into an array:

mapfile -t fnames < <(tr ',' '\n' < file)
touch "${fnames[@]/%/.md}"

The parameter expansion ${fnames[@]/%/.md} replaces the end of each array element (%) with suffix .md.

  • This works. But why does touch {file1,file2}.md create file1.md and file2.md while using cat it doesn't?
    – TitanX
    Apr 7 '20 at 16:14
  • The brace expansion is evaluated before the command substitution of $(cat file). You could do an ugly eval like eval "touch {$(cat file)}.md" instead...
    – Freddy
    Apr 7 '20 at 16:23
  • Is there any advantage in converting to newline separated format and then using mapfile, compared to say IFS=, read -a fnames < file ? Apr 7 '20 at 17:16
  • @steeldriver Not if the file only contains one line.
    – Freddy
    Apr 7 '20 at 17:24

Just convert the comma to a newline and then read the file names:

sed 's/,/\n/g' file | while read fileName; do touch "$fileName".md; done


tr , '\n' < file | while read fileName; do touch "$fileName".md; done
  • Thanks for this! But do you know why touch {$(cat file)}.md doesn't work?
    – TitanX
    Apr 7 '20 at 16:01
  • @TitanX it does work. You are telling it to create a file whose name is the contents of file. Those contents are file1,file2 so that's what it creates.
    – terdon
    Apr 7 '20 at 16:06
  • But touch {file1,file2}.md creates two different files file1.md and file2.md and cat file exactly returns file1,file2
    – TitanX
    Apr 7 '20 at 16:12

You can try something like this:

tr ',' '\n' < file | xargs -0 -I {} touch {}.md
  • This creates one file with two newlines. Have you tried?
    – Freddy
    Apr 7 '20 at 16:39
  • @Freddy Yes I have, and in my tests it creates files separately Apr 7 '20 at 16:47
  • I'm copying the command as it is in my answer to discard doubts, and copied the string of files from the question. Apr 7 '20 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.