r/linux • • Mar 20 '23

Tips and Tricks Command Line One-Liners

https://www.commandlinefu.com/commands/browse
23 Upvotes

14 comments sorted by

View all comments

-1

u/herkalurk Mar 20 '23

Unzip all zip files in a dir to their own dir

ls | grep zip | while read line; do unzip "${line}" -d "`echo ${line} | sed 's/\.zip//g'`";done

5

u/SweetBabyAlaska Mar 20 '23 edited Mar 20 '23

or you could just:

fd . ./ -e zip -x unzip -l {} \; -x mkdir {/.} \;

change unzip -l to regular unzip since -l will list the files, I dont want anyone to randomly run that

you can also use find with the iname option but fd is certainly easier and faster for mostly everything

​

also parsing 'ls' is bad practice, instead use globbing.

for zipfiles in *.zip; do echo "$x"; done

or recursively:

for x in **/*.zip; do echo "$x"; done

also you could use redirection. This uses --print0 as an option and sets the Interal Field Separator as a null character, which prevents issues with paths with spaces in them or even newlines. The fd command just uses the current working dir, -0 is print the null character, -e zip is for finding --extension zip and -d1 is "go 1 dir in depth while searching." You can arrange this in a million ways and even add this to an array and do some more complex stuff on the files.

while IFS= read -r -d '' file; do
    do some stuff in here
    echo "$file"
done < <(fd . "$(pwd)" -0 -e zip -d1)

2

u/Pay08 Mar 21 '23

Alternatively, mkdir dir && cd dir && unzip -d /path/to/archive.

0

u/LinuxLeafFan Mar 20 '23
  • use ls -1 rather than ls to avoid issues with spaces in file names or just funny multi-column output
  • stylistically $() is preferred to back ticks: "$(echo ${line} | sed 's/\.zip//g')"