0

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 !!

ShivaGaire
  • 2,283
  • 1
  • 20
  • 31
Anshul Arora
  • 15
  • 1
  • 5

1 Answers1

0

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
Eduard Itrich
  • 836
  • 1
  • 8
  • 20
  • This method does not work when the file name has a white space. Better use: https://stackoverflow.com/a/9612560 – wouter205 Jan 27 '21 at 16:48
  • +1 @wouter205 Comment - The For Loop has its Restrictions and i have faced issues with it , Right way to go is as u suggested Find and While do Loop - https://stackoverflow.com/a/9612560 , Kudos :) – BetaCoder Mar 15 '21 at 14:36
  • @BetaCoder you're welcome, it did take me some time to figure it out so I wanted to help others to prevent this :-) – wouter205 Mar 22 '21 at 11:19