Search code examples
linuxshellcopyfilepathpartial

How to copy files and preserve partial paths in Linux?


It's easy to copy files and preserve the full path as the source using --parent. Didn't find questions and solutions on how to preserve partial paths, keep the partial path and filename in lowercase as below,

Source: /A/B/c/d/e.txt

Target: /X/Y/c/d/e.txt

The only/dumb way I can think of is to parse out "c/d" from the source, and then "mkdir -p /X/Y/c/d"and "cp /A/B/c/d/e.txt /X/Y/c/d". Is there a better single-liner way without all the pre/postfix string operations?


Solution

  • A simple way would be to first cd (or pushd/popd) into /A/B, then let the -t (--target-directory) option replicate the relative path hierarchy.

    cd /A/B && cp -t /X/Y --parents c/d/e.txt