shellunixunrar

extract rar files to same folder name


I have many .rar folders within a particular directory. I want to extract contents of each rar folder in the same directory and all the extracted files of rar folder should be placed in the new folder with the same name as that of the rar folder name.

For example, if there are two rar files: one.rar and two.rar, then the script should create two folders of the same name: one and two. A folder named one should contain files extracted from one.rar and folder named two should contain files extracted from two.rar.

The command: unrar e $filename extracts all the contents of rar file but does not create a destination folder.

If I use unrar e $filename $DESTINATION_PATH, then since there can be many rar files, manually creating the folder name in the destination path will take a lot of time. How can I achieve this with a shell script?

so far I have written only these lines:

loc="/home/Desktop/code"`  # this directory path contains all the rar files to be extracted  <br/>

for file in "$loc"/* 
do               
unrar e $file
done

I don't know how to create the same folder name as of rar name and extract all files of that rar in the newly created folder of the same name.

Any help will be appreciated. Thanks in advance !!


Solution

  • You can use sed to remove the file extension from your archives. Look at the following script which sets destination to the corresponding name.

    #!/bin/sh
    
    for archive in "$(find $loc -name '*.rar')"; do
      destination="$( echo $archive | sed -e 's/.rar//')"
      if [ ! -d "$destination" ] ; then mkdir "$destination"; fi
      unrar e "$archive" "$destination"
    done
    

    If you're using bash, then you can simply use

    #!/bin/bash
    
    for archive in "$(find $loc -name '*.rar')"; do
      destination="${archive%.rar}"
      if [ ! -d "$destination" ] ; then mkdir "$destination"; fi
      unrar e "$archive" "$destination"
    done