3

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.

My Work
  • 137

1 Answers1

2

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

Ravexina
  • 57,256