How to unzip a .zip file to all directories that contain a .php file that contains the text "house" inside?

Something like:

grep -rl --include='index.php' 'house' /directory/path/of_the_index_file* | xargs unzip /directory2/path/file.zip -d /directory/path/of_the_index_file/

CLARIFICATION: I simply want to extract a simple .zip file with 2 files and one directory, to all directories on the server that contain an index.php file with a specific string inside of its code.

I'd be very grateful for any help.


You could use xargs sh -c '...' together with $(dirname "$1"):

grep -rlZ --include='index.php' house /directory/path/of_the_index_file* \
| xargs -0 -I{} sh -c 'unzip /directory2/path/file.zip -d "$(dirname "$1")"' xargs-sh {}

Or easier, use GNU parallel, which has dirname feature included using {//}:

grep -rlZ --include='index.php' house /directory/path/of_the_index_file* \
| parallel -0 -n1 unzip /directory2/path/file.zip -d {//}

Avoid parallelization if you want by adding -j1 to parallel.

If parallel is not installed, install it using:

sudo apt install parallel

You might consider running unzip once in the beginning to a temporary directory and use cp or ln inside xargs or parallel.

Note: For both solutions, I use grep -Z together with xargs/parallel -0 to avoid problems with newlines somewhere in the path. Even if it does not affect you, it's a good habit to take care of it.

  • since you used grep -r --include over find as I did in my parallel answer (unix.stackexchange.com/a/551736/123460). Any idea regarding speed? Also could you explain find-sh and why you would not need -n1 in xargs? – FelixJN Nov 12 '19 at 12:55
  • 1
    Regarding find-sh, see https://unix.stackexchange.com/questions/156008/is-it-possible-to-use-find-exec-sh-c-safely. -I implies -L1, which is similar to -n1 but based on lines instead of arguments. Unzipping before and using cpor ln should be faster. grep -rl should be faster than find -exec grep ... and is shorter to write, but it may be a matter of choice... – pLumo Nov 12 '19 at 13:01
  • Actually, find-sh should be xargs-sh, my fault ;-) It doesn't matter much if it works, but it is good regarding useful error messages... But anyways, parallel is easier ;-) – pLumo Nov 12 '19 at 13:05
  • Thank you pLumo..I tried the code but it showed me the error: -jailshell: parallel: command not found – Jaro Nov 12 '19 at 13:25
  • I thought parallel was installed by default in Ubuntu, seems not the case, but you can easily install it. – pLumo Nov 12 '19 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.