There are many folders that are in a specific directory. In these folders, I look for files with a specific extension, *.txt for example. The task is to find those folders in which there is at least one txt file and copy this folder to another directory, for example txtfiles . I tried to just find a file and archive with the command

 tar cf txts.tar `find /root/test/1/ -name '*.txt' ` 

But it adds only txt files to the archive, but I need a full copy of the folder with them (if txt is in /root/test/1/2/3/path /root/txtfiles /root/test/1/2/3/path , then I need to copy the whole folder 1 into /root/txtfiles from all files and directories attached to it).

  • find output send ( | ) say sed, which cut the beginning of the path to the desired depth (say, focusing on / ). send all this to sort and uniq to get all the folders exactly one time - Mike

2 answers 2

 #!/bin/sh rootdir="/d/tmp/123" outdir="/d/tmp/txtfiles" mkdir -p "$outdir" pushd "$rootdir" find . -mindepth 2 -name '*.txt' | xargs dirname | xargs -I{} cp -R --parents {} "$outdir" popd 

In the rootdir variable, we set the directory, in the subdirectories of which we will search for txt files, the found directories are copied to outdir while the structure is saved with the command cp -R --parents .

  • It copies only txt files, the rest of the files in the folder are not. This is the main problem. How can I make sure that all other files are also saved when copying? - quzty
  • @quzty fixed - kmv

If we proceed from the minimum modification of your team:

 $ tar -cf txts.tar $(find /root/test/1/ -name '*.txt') 

you can add the -printf '%h\n' option to the other find options of the program and remove duplicates from the find results using the sort program:

 $ tar -cf txts.tar $(find /root/test/1/ -name '*.txt' -printf '%h\n' | sort -u) 

see the man find and man sort details.