cp has a useful feature --parents that allows a file’s directory structure to be copied to another directory:
$ cp -v --parents source/directory/from target/ ‘source/directory/from’ -> ‘target/source/directory/from’
How do I similarly move a file?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Not directly, at least not for GNU mv according to its man page. A possible workaround would be adding a function like this:
pmv(){
source=$1
target=${2%/}
mkdir -p -- "$target/$(dirname -- "$source")" &&
mv -- "$source" "$target/$(dirname -- "$source")/"
}
Add that function to your shell’s configuration file (~/.bashrc if you are using bash) and run it like this:
pmv source/directory/from target/
Method 2
Is there a way to move a file in a similar fashion?
None. mv is rather simple utility which uses system call rename (atomic FS operation) if possible — when source/destination are on the same block device, otherwise it falls back to cp behavior. Actually rename would fail even if you src/dst are the same device mounted to different mount points which Linux does allow.
So, when you need to move files like:
cp -v --parents source/directory/from target/
you can just think of:
mv source target/
but keep in mind that it would move the whole content all the parents dir could have inside along the way, so you’d need to deal with that later — I mean unlinking all those extra-files if you need to have the same result as cp --parents would provide.
Sooner or later you’d realize, that what you’re doing could be easily accomplished with cp/rm approach instead. And cp‘s -l can be used to make it working fast, meanwhile allowing to use beloved --parents. That’s the reason mv wouldn’t have anything such fancy as cp‘s --parents.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0