Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a shell script to remove the unzipped files in a wrong directory?

Tags:

shell

I accidentally unzipped files into a wrong directory, actually there are hundreds of files... now the directory is messed up with the original files and the wrongly unzip files. I want to pick the unzipped files and remove them using shell script, e.g.

$unzip foo.zip -d test_dir
$cd target_dir
$ls test_dir | rm -rf

nothing happened, no files were deleted, what's wrong with my command ? Thanks !

like image 354
Yifan Zhang Avatar asked Jan 27 '12 08:01

Yifan Zhang


2 Answers

The following script has two main benefits over the other answers thus far:

  1. It does not require you to unzip a whole 2nd copy to a temp dir (I just list the file names)
  2. It works on files that may contain spaces (parsing ls will break on spaces)

while read -r _ _ _ file; do
  arr+=("$file")
done < <(unzip -qql foo.zip)
rm -f "${arr[@]}"
like image 138
SiegeX Avatar answered Nov 15 '22 10:11

SiegeX


Right way to do this is with xargs:

$find ./test_dir -print | xargs rm -rf

Edited Thanks SiegeX to explain to me OP question.

This 'read' wrong files from test dir and remove its from target dir.

$unzip foo.zip -d /path_to/test_dir
$cd target_dir
(cd /path_to/test_dir ; find ./ -type f -print0 ) | xargs -0 rm 

I use find -0 because filenames can contain blanks and newlines. But if not is your case, you can run with ls:

$unzip foo.zip -d /path_to/test_dir
$cd target_dir
(cd /path_to/test_dir ; ls ) | xargs rm -rf

before to execute you should test script changing rm by echo

like image 35
dani herrera Avatar answered Nov 15 '22 09:11

dani herrera