Search code examples
unixarchivetar

tarballing only directories which match pattern


I have a parent directory, within which there are many many subfolders and in each of those subfolders is a directory called "start". I somehow want to make a tarball from the parent directory and have it only include the directories called "start" but to maintain the parent directory sub-structure. How can I do this?


Solution

  • Assuming Bash, you can use extended globbing to select only the wanted subdirectories.

    Exemple: Let's create a dummy directory hierarchy

    $ mkdir -p test/{top,bottom}/{start,finish}/{one,two}
    $ find test
    test
    test/bottom
    test/bottom/finish
    test/bottom/finish/one
    test/bottom/finish/two
    test/bottom/start
    test/bottom/start/one
    test/bottom/start/two
    test/top
    test/top/finish
    test/top/finish/one
    test/top/finish/two
    test/top/start
    test/top/start/one
    test/top/start/two
    

    Now, to create a tar archive with only directories start and their content:

    $ tar cvf test.tar test/**/start
    a test/bottom/start
    a test/bottom/start/one
    a test/bottom/start/two
    a test/top/start
    a test/top/start/one
    a test/top/start/two
    $ 
    

    Note that extended globbing must be enable to use this solution.

    $ shopt extglob
    extglob         on
    

    If it is not enabled, use

    $ shopt -s extglob