I would like to recursively search a folder, extract the RAR file, and remove .nfo, .svf and the RAR files (*.rar and *.r1, *.r2, etc).

I found a command to recursively extract, but not to remove:

find ./ -name '*.rar' -exec unrar e {} \;

Tack another -exec predicate (with rm inside that), which would only be run if the first one succeeds:

find . -name '*.rar' -exec unrar e {} \; -exec rm {} \;

-exec rm {} \; will only be run to remove the .rar file if the unrar-ing succeeds (-exec unrar e {} \;) i.e. unrar returns with exit status 0.

You can also do this using bash, using globstar option to recursively match glob pattern (*.rar), and rm each file if unrar-ing is successful:

shopt -s globstar
for f in **/*.rar; do
    unrar e "$f" && rm "$f"
  • Alright thanks! I ran find . -name '*.rar' -exec unrar e {} \; -exec rm {} \; on a test folder, containing a divided rar archive. *.r01, *.r02, *.r03 etc, and ofc the *.rar file. The *.rar file was deleted, but not the rest of the archive. The rar segment files was still there (.r01,r02,r03,r04..) – Adam Apr 10 '17 at 14:56
  • @Adam You are matching only the .rar files with -name '*.rar', try: find . -regextype posix-egrep -regex '.*\.r([[:digit:]]+|ar)$' -exec unrar e {} \; -exec rm {} \; – heemayl Apr 10 '17 at 15:09
  • Thanks once again! But now I seems to try to unrar all segments. Maybe find the rar, and delete the rar and .*\.r([[:digit:]]+|ar)$? – Adam Apr 10 '17 at 17:52
  • @Adam I see, just append the removal of the segments upon success: find . -name '*.rar' -exec unrar e {} \; -exec rm {} \; && rm *.r+([[:digit:]]) (assuming extglob option of bash is set, which is the default, otherwise set with shopt -s extglob first) – heemayl Apr 10 '17 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.