2

I've used touch for single creation of blank files and multiple blank files from a list using cat foo.txt | xargs touch plus I ran across How to create multiple files with the Terminal? but I'm having issues figuring out how I can implement the creation of files that use a template from a list of files with pure bash.

File names in foo.txt file:

cpt-one.php
cpt-two.php
cpt-three.php

template.txt:

// lots of code

Is there a way I can use touch to create the file's from the list using what's in template.txt instead of creating a blank file?

user9447
  • 1,945
  • 5
  • 27
  • 41

2 Answers2

4

A bash-esque way to do it (without an explicit loop) might be

  • read the filenames into a shell array variable

    mapfile -t files < foo.txt
    

    or its synonym readarray -t files < foo.txt

  • expand the array inside a tee command

    tee < template.txt -- "${files[@]}" > /dev/null
    

[The > /dev/null is optional - it just hides tee's default standard output from the terminal.]

steeldriver
  • 142,475
0

Unless you have thousands of files that you need to create, you can use brace expansion:

$> touch cpt-{one,two,three}.php
$> ls
cpt-one.php  cpt-three.php  cpt-two.php

Since your objective is to clone template , use tee to redirect stdin to multiple files. tee writes to both file and stdout, so you will see it echoed on the terminal

$> cat template.txt  | tee cpt-{one,two,three}.php                             
I'm template

Alternatively , one could use while read structure. with shell redirection.

$> rm *
$> vi inputFile.txt
$> while read FILE; do touch "$FILE" ; done < inputFile.txt
$> ls
cpt-one  cpt-three  cpt-two  inputFile.txt

Note well, that this is a simple example, that assumes entries in the file contain no special chars

Now, since you actually want to copy single file in to multiple, you can use the same structure, to cp /path/to/template "$FILE"

$> ls
inputFile.txt  template.txt
$> cat template.txt                                                            
I'm template
$> while read FILE; do cp template.txt "$FILE" ; done < inputFile.txt            
$> cat cpt-one.php                                                             
I'm template
$> 
kos
  • 41,268