John Bokma

Tar files located in another directory

August 2, 2016

Today I wanted to send some PDF files on blogging to a friend. I have those files in a "Blogging" directory which I can access using WebDAV with SSL on my iPad. I use this set up to sync PDF books to the GoodReader iOS app, which I can't recommend enough if you want to read PDFs on an iPad.

I wanted to add the files into a single compressed tar file for easy uploading / downloading but I didn't want to create this tar file inside this directory to prevent cluttering it. Moreover, the "Blogging" directory is owned by user www-data and I wanted to avoid using sudo and chown. In short, my requirement was to create the tar file in a different location. And without the path information.

So, at first I tried the -C option of tar to change to the directory containing the desired PDF files:

tar zcvf blogging.tgz -C ~/Downloads/GoodReader/Computer/Blogging .

However, this command has the disadvantage that the resulting tar file has a directory named . (dot) which contains the desired PDF files.

After some Googling I did find a solution: use the --transform option of tar to transform the file names using sed.

So I used the sed substitute command s to delete all characters of the file name of each PDF file up until and including the final forward slash. Because the pattern on the left hand side has a slash I use ? as a delimiter to avoid a 'picket fence'.

tar zcvf blogging.tgz ~/Downloads/GoodReader/Computer/Blogging/*.pdf \
  --transform 's?.*/??'

And this command did exactly what I wanted. Note that this solution allows for filename expansion (globbing), unlike the previous one. For example, I use *.pdf to add only files with the pdf extension to the compressed tar file.

home - blog - email

I am a freelance Perl programmer for hire, download my up-to-date resume (PDF).