Search code examples
listshelltouchdirectorymkdir

Shell script to create directories and files from a list of file names


I'm (still) not a shell-wizard, but I'm trying to find a way to create directories and files from a list of file names.

Let's take this source file (source.txt) as an example:

README.md
foo/index.html

  foo/bar/README.md
foo/bar/index.html

foo/baz/README.md

I'll use this command to remove empty lines and trim useless spaces:

$ more source.txt | sed '/^$/d;s/^ *//;s/ *$//'

It will give me this list:

README.md
foo/index.html
foo/bar/README.md
foo/bar/index.html
foo/baz/README.md

Now I'm trying to loop on every line and create the related file (it it doesn't already exists), with it's parents directories.

How could I do this?
Ideally, I would put this script in an alias to quickly use it.


Solution

  • As always, posting a question brings me to the end of the problem...

    I came to a satisfying solution, using dirname and basename in a for .. in loop:

    for i in `cat source.txt | sed '/^$/d;s/^ *//;s/ *$//'`; 
      do mkdir -p `dirname $i`; 
         touch `echo $(dirname $i)$(echo "/")$(basename $i)`; 
      done
    

    This one-line command will:

    • read the file names list
    • create directories
    • create empty files in their own directory