简体   繁体   English

在使用tar提取文件时,如何在通配符上使用OR运算符

[英]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. 虽然我可以找到一个文件夹中的所有.tgz文件,然后从该文件中仅提取PDF,EPUB和MOBI文件(如果它存在于存档中)。

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. 当归档文件中包含pdf,mobi或epub时,此行代码可以完美工作。 However with this code, whenever there is no pdf / epub / mobi within given archive it returns an error as shown below. 但是,使用此代码,只要给定存档中没有pdf / epub / mobi,它就会返回错误,如下所示。

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. 我相信应该有一种方法可以像其他脚本语言一样为多个通配符提供一个“ OR”运算符。

tar isn't a scripting language. tar不是脚本语言。

To hide the error message, just redirect the stderr of tar to a bit bucket: 要隐藏错误消息,只需将tar的stderr重定向到位存储桶:

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\)$'

Thanks to @choroba below code is perfect. 感谢@choroba,下面的代码非常完美。 No error reported. 没有错误报告。 Posting the code as answer so that others have better visibility to the final working piece of code. 将代码发布为答案,以便其他人可以更好地查看最终代码。

find '/home/pi/Downloads/complete/' -type f -name "*.tgz"| while read i ; do tar --list -f "$i" | grep '\.\(pdf\|mobi\|epub\)$' | while read -r line ; do  tar -kxvzf "$i" -C "/home/pi/Downloads/complete/ebook/" "$line" --strip=1;done; done;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM