Ankit Ankit - 3 months ago 10
Linux Question

How to use OR operator with wildcards while extracting files with tar

While I can find all the .tgz files within a folder and then extract only PDF, EPUB and MOBI files from it if it is present in the archive.

find '/home/pi/Downloads/complete/' -type f -name "*.tgz"| while read i ; do tar -xvzf "$i" -C /home/pi/Downloads/complete/ebook/ --strip=1 --wildcards --no-anchored '*.pdf' '*.mobi' '*.epub'; done


This line of code works perfectly when either of pdf, mobi or epub is present in the archive. However with this code, whenever there is no pdf / epub / mobi within given archive it returns an error as shown below.

tar: *.pdf: Not found in archive
tar: *.mobi: Not found in archive
tar: Exiting with failure status due to previous errors


How to prevent this error. I believe there should be a way to provide the multiple wildcards with a 'OR' operator as available in other scripting languages.

Answer

tar isn't a scripting language.

To hide the error message, just redirect the stderr of tar to a bit bucket:

tar ... 2> /dev/null

Note that you might miss other errors, though.

The safe way would be to list the files first, select the ones to extract, and only do that if there were any.

tar --list -f ...tgz | grep '\.\(pdf\|mobi\|epub\)$'