Search code examples
linuxshellfindxargs

Tar a list of files under a sub directory of another directory


How do I tar a list of files by name SOME_FILE_NAME that are under SUB_FOLDER of folder SOME_FOLDER. I use following command to list the files

find <SOME_FOLDER> -name <SUB_FOLDER> -execdir realpath "{}" ';' | xargs -I p find p -name <SOME_FILE_NAME>

For example, following command lists 3 files that I want to tar

Command:

find /logs/ -name app-2018 -execdir realpath "{}" ';' | xargs -I p find p -name stdout

Output:

/logs/app-2018/2/stdout
/logs/app-2018/0/stdout
/logs/app-2018/1/stdout

The result should tar above 3 files.


Solution

  • Use -path to match a file's full path. You can check both the file name and the directory it's contained in with one check.

    find /logs/ -path '*/app-2018/*/stdout' -exec tar -cf logs.tar {} +