cs

Simple Unrar Code

October 25, 2019

I want to find a command line code or bash script to unrar all the files in subfolder. This is can be easily done by:

1
find Photos/ -name '*.rar' -execdir unrar e {} \;

However, this will output all unzipped files in current folder. Then I tried a script from here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#! /bin/sh

# ref: http://bashscripts.org/forum/viewtopic.php?f=8&t=908
# ref : http://www.linuxquestions.org/questions/programming-9/unrar-multiple-files-into-seprated-directory-base-on-their-name-927127/

echo "starting unrar in folders"

# for everything named *.rar
for filename in *.rar

    do

        foldername=$(basename "$filename" .rar)
        echo $foldername
        mkdir "$foldername"
        cd "$foldername"
        unrar x ../"$filename"
        cd ..

    done

echo "finished unrar in folders"

Note that cd doesn’t simply work in bash script if you call it like ./cdscript. Instead, you can do . ./cdscript. See here for details.

Then I found this approach also has limitations since in my subdirectories, all zip files have same name, and all files in zip files have same names. Something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
subdirA
    - A.zip
        - a.csv
        - b.csv
        - c.csv
    - B.zip
        - a.csv
        - b.csv
        - c.csv

subdirB
- A.zip
    - a.csv
    - b.csv
    - c.csv
- B.zip
    - a.csv
    - b.csv
    - c.csv

...

Then I modified the script without cd, then it works perfectly!

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash

for filename in $( find . -name '*.rar' )
    do
        foldername=${filename%.*}            # remove the rar suffix
        mkdir "$foldername"
        unrar e "$filename" "$foldername"    # unrar to a specific folder
        echo "------------分割线------------" # separating line
    done