Home page Ubuntu C++ Hardware HTML i javascript Java Software SQL

Awk|Bash – extracting files from rar and after ended operation deleting archive files.

Added: 2012-10-26

By downloading a large number of rar archive files, is useful script, that searches the folder in order to search for compressed files, and after finding their extracts all files from archives.

The script has one argument (optional), is path to folder where are archives rar. The script without argument starts the search in current folder.

Below script:

./unrarb.bash /home/user/Downloads

#!/bin/bash

echo "The script extract files from rar archives and delets them, after operation completes successfully.";


if [ "$1" = ""  ]; then
	DEST=`pwd`"/";
else
	if [ ! -d $1 ]; then
		echo "";
		echo "The argument \""$1"\" is not directory!!!";
		echo "";
		exit 1;
	fi;
	DEST=$1"/";
fi;

echo "Start working in: \""$DEST"\"";

for FF in $DEST*; do
	echo `basename "$FF"` | awk 'BEGIN{}{		
		extr = 0;
		if (substr($0, length($0)-3, 4) == ".rar"){
			if (index($0, ".part1.rar") != 0){
				extr = 2;
			} else if (index($0, ".part") == 0)
				extr = 1;

			if (extr != 0){
				print "Extracting file: \""$0"\"";
				system("unrar x -o+ '"$DEST"'"$0" '"$DEST"';");
				if (extr == 1)
					system("if [ \"$?\"  -eq \"0\" ]; then rm \"'"$DEST"'"$0"\"; fi;");
				else {
					for (i=1; ;i++){
						files=substr($0, 0, index($0, ".part"));
						files=files".part"i".rar";
						if (system("[ -f \"'"$DEST"'"files"\" ]") == 0)
							system("if [ \"$?\"  -eq \"0\" ]; then rm \"'"$DEST"'"files"\"; fi;");
						else
							break;
					}		
				}
			}
		}
	}';
done;

echo "";
echo "End script.";