How to write a shell script to delete unpacked files in the wrong directory?

I accidentally unpacked the files into the wrong directory, in fact there are hundreds of files ... now the directory is messed up with the source files and it is unpacking the files incorrectly. I want to select the unpacked files and delete them using a shell script, for example.

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

nothing happened, files were not deleted, what happened to my team? Thanks!

+6
source share
7 answers

The following script has two main advantages over other answers:

  • This does not require you to unzip the whole second copy in dir temp (I just list the file names)
  • It works with files that may contain spaces (parsing ls will be split into spaces)

 while read -r _ _ _ file; do arr+=("$file") done < <(unzip -qql foo.zip) rm -f "${arr[@]}" 
+6
source

The correct way to do this is with xargs:

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

Edited Thanks to SiegeX to explain the OP question to me.

This is "reading" the wrong files from the test directory and removing it from the target directory.

 $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 file names can contain spaces and newlines. But if that is not the case, you can start using ls :

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

before execution you should check the script change rm to echo

+1
source

Try

  for file in $( unzip -qql FILE.zip | awk '{ print $4 }'); do rm -rf DIR/YOU/MESSED/UP/$file done 

unzip -l specify contents with information about files with zip files. You just need the grep file name from it.

EDIT: using -qql as suggested by SiegeX

+1
source

Do it:

 $ ls test_dir | xargs rm -rf 
0
source

Do you need ls test_dir | xargs rm -rf ls test_dir | xargs rm -rf as your last command

Why:

rm does not accept input from stdin, so you cannot pass a list of files to it. xargs displays the result of the ls and presents it in rm as input so that it can delete it.

0
source

Seal the previous one. Run this command in / DIR / YOU / MESSED / UP

 unzip -qql FILE.zip | awk '{print "rm -rf " $4 }' | sh 

to use

0
source

The following worked for me (bash)

 unzip -l filename.zip | awk '{print $NF}' | xargs rm -Rf 
0
source

Source: https://habr.com/ru/post/907002/


All Articles