0

I'm having a hard time trying to limit the path with find.

I have this command find ${DIR_PATH} -type f -name ".py" -exec cp --parent {} ${DEST_DIR} \;

Which give me this output :

${DIR_PATH}/a/main.py
${DIR_PATH}/a/b/resources.py
${DIR_PATH}/c/__init__.py
${DIR_PATH}/c/main.py

I definitely know ${DIR_PATH} as I am looking in this directory. How can I get :

a/main.py
a/b/resources.py
c/__init__.py
c/main.py

The objective is to get the following in the destination directory :

${DEST_DIR}/a/main.py
${DEST_DIR}/a/b/resources.py
${DEST_DIR}/c/__init__.py
${DEST_DIR}/c/main.py

But I have this instead :

${DEST_DIR}/${DIR_PATH}/a/main.py
${DEST_DIR}/${DIR_PATH}/a/b/resources.py
${DEST_DIR}/${DIR_PATH}/c/__init__.py
${DEST_DIR}/${DIR_PATH}/c/main.py

Note : DIR_PATH and DEST_DIR are set up at the beginning of a sh file.

1 Answer 1

1

If ${DEST_DIR} is an absolute path, one way could be to cd to ${DIR_PATH} before running find on the current directory. This way, the paths from find will all be relative:

cd "${DIR_PATH}"
find . -type f -name ".py" -exec cp --parent {} "${DEST_DIR}" \;

(If DEST_DIR isn't an absolute path, prefix it with $PWD from before the cd.)

You could instead use rsync. Something like:

rsync -a --prune-empty-dirs --include "*/"  --include="*.py" --exclude="*"  "${DIR_PATH}/" "${DEST_DIR}" 

(Note the trailing slash after ${DIR_PATH})

2
  • Thank you muru ! This works perfectly, I prefer not to use rsync as I use it later. Otherwise it will be confusing for me.
    – user359435
    Jun 25, 2019 at 9:22
  • 1
    Note that if you change a find command to something like find . -type f -name ".py" -exec cp --parent -t "${DEST_DIR}" {} \+ it won't execute separate cp for each and every file which might significantly speed the execution.
    – rush
    Jun 25, 2019 at 9:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .