1

I have directory A and B. Each of them contains another directory with item.json inside. Only item.json file is persistent in directories so I can't copy-paste the directories.

A:

./path/Item A/item.json
./path/Item B/item.json
...
./path/Item Z/item.json

B:

./new/Item A/item.json
./new/Item B/item.json
...
./new/Item Z/item.json

How should I copy all item.json files from ./path/ to appropriate folders in ./new ?

My solution:

To get directories

ls -l ./path | grep "^d" | cut -d' ' -f 16

So then I can use the results as:

for i in `ls -l ./path | grep "^d" | cut -d' ' -f 16`; echo "Dir: $i"; done

So I can do cp with them

for i in `ls -l ./path | grep "^d" | cut -d' ' -f 16`; cp "$i/item.json" "../new/$i/item.json" ; done

And this solution is ok, but I believe there's much more elegant way.

  • 1
    find ./path -type d -exec cp -rt ./new {} + – Costas Feb 17 '15 at 10:45
1

Your solution is fine! If you like to see alternatives, my suggestion is just cp!

I presume you want to copy just "item.json" files and that you can have other contents not to be copied.

cd path; cp --parents */item.json ../new
2

Below one liner should help you with it.

$ find ./path/ -type f -exec bash -c 'cp $0 ${0/path/new}' {} \;

Here the find command searches for all text file within the ./path/ directory. When a file is found it invokes a small bash script which copies that file to the destination /new/ directory by just replacing string from path to new.

1

Use cpio (or tar, but IMHO it slower and don't have -p option like cpio do)! It maintains permissions, dates, etc. (if asked to) and of course maintains directory structure.

I.e.: cd path ; find . | cpio -pvmd ../new

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.