Using "parents" command works but it copies complete directory structure, whereas I need to preseve only the last most directory

find /tmp/data/ -type f -name "*.txt" -exec cp --parents {} /u01/ABC/ \;

Output that I get:


Output that I need:


You could use sh -c in your find -exec command, then you have more control, e.g. to do something like this:

find ... -exec sh -c '
    target="/u01/ABC/$(basename "$(dirname "$1")")"
    mkdir -p "$target" && cp --backup "$1" "$target"
' find-sh {} \;

You can cd into the target directory and run the find command from there:

cd /tmp/data; find . -type f -name "*.txt" -exec cp --parents {} /u01/ABC/ \;

If you need to get back to your original working directory, you can do a cd - afterwards or run the command in a subshell:

(cd /tmp/data; find . -type f -name "*.txt" -exec cp --parents {} /u01/ABC/ \;)
  • this is what I was looking for , thanks Freddy !!! – amit ghosh May 21 at 7:33

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.