I have a list of files I would like to remove from where they are currently located, and hopefully restore them back to their original locations. For about a minute, I thought about trying to write a one-liner using mv or cp, but I know mv doesn't mkdir for you, thanks for nothing mv. Then I though, archives rebuild file structures when they don't exist. So, tar to the rescue. Sorry, not today bash.

Let get started in a small demonstration of what I'm talking about.

PS. These instructions were preformed on a Mac, intending to be ultimately ran on Linux. I'm sure the same concept would work on Windows with WinZip/7zip/WinRAR.

Setting Up Some Dummy Files

Lets create a nested directory with some dummy files, all inside the tmp directory to be safe.

cd /tmp
mkdir -p bckp-n-rstr/a/b/c/d
touch ./bckp-n-rstr/a/b/c/d/test-{1..5}.txt

Nice, a quick find ./bckp-n-rstr/**/. >> allfiles.txt && cat allfiles.txt should push the list of files to a txt file for you, and print out the list so you can see what's going on. The output should look like this...

./bckp-n-rstr/a/b/c/d/test-1.txt
./bckp-n-rstr/a/b/c/d/test-2.txt
./bckp-n-rstr/a/b/c/d/test-3.txt
./bckp-n-rstr/a/b/c/d/test-4.txt
./bckp-n-rstr/a/b/c/d/test-5.txt

Archive & Remove The Files Listed

We can use the -T flag to point to the list of files file.

tar -cvf allfiles.tar -T allfiles.txt
You can see what's now in the tar file by running tar -tvf allfiles.tar.

Now time to remove the files.

xargs rm -rf <allfiles.txt
This will only remove the files, not directories.

All gone. find ./bckp-n-rstr/**/*.*

Restore Everything Back to Normal

Time to get everything back, it's simple enough.

tar -xvf allfiles.tar

All back. find ./bckp-n-rstr/**/*.*

./bckp-n-rstr/a/b/c/d/test-1.txt
./bckp-n-rstr/a/b/c/d/test-2.txt
./bckp-n-rstr/a/b/c/d/test-3.txt
./bckp-n-rstr/a/b/c/d/test-4.txt
./bckp-n-rstr/a/b/c/d/test-5.txt

Simple... and painless.