1

I have 2-3 levels and several folders but in all is a file with the name L_data.txt (among other files). I would like to copy only those L_data.txt together with their parent folders without any of the other files to another place. How can I do that?

E.g.:

./PycharmProjects/folderA/L_data.txt
./PycharmProjects/folderB/L_data.txt
.
.
./PycharmProjectsCluster/folderQ/L_data.txt
./PycharmProjectsCluster/folderR/L_data.txt
.
.

I have found this post and this post but that moves all files without the folders. Thanks for help.

0

Let’s say I want a copy of each L_data.txt in new_dir with its parents preserved. Here is my directory structure right now:

$ tree
.
├── new_dir
├── PycharmProjects
│   ├── folderA
│   │   ├── foo.txt
│   │   └── L_data.txt
│   └── folderB
│       ├── foo.txt
│       └── L_data.txt
└── PycharmProjectsCluster
    └── folderQ
        ├── foo.txt
        └── L_data.txt

6 directories, 6 files

You can see that I have two file in each directory, L_data.txt and foo.txt.

We can use find command to find all files named L_data.txt. Then using its --exec option we will run cp --parents so it copies the files into the new destination while keeping their parents.

find . -name L_data.txt -exec cp --parents -t new_dir/ {} +

The result:

$ tree new_dir/
new_dir/
├── PycharmProjects
│   ├── folderA
│   │   └── L_data.txt
│   └── folderB
│       └── L_data.txt
└── PycharmProjectsCluster
    └── folderQ
        └── L_data.txt

5 directories, 3 files
4
  • Hi, thank you for your answer but for some reason, it does not work. Listing the files as find . -name L_data.txt works but when I use the full command, it freezes and does not copy. – My Work Jun 22 '20 at 12:17
  • EDIT: it works if levels are only 2 but not 3. – My Work Jun 22 '20 at 12:41
  • Please edit your question and add an example that does not work. – Ravexina Jun 22 '20 at 18:33
  • find . -name L_data.txt -exec cp --parents -t new_dir/ {} \; instead of the proposed seems to work. Then I have another problem with the find itself with which I do not want to spam here. Thanks again. – My Work Jun 23 '20 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.