Question

I have 5 zip files and inside each of them are a few .txt files and a few others. I want to unzip only those files with extension .txt, but in the first iteration of the loop unzip runs correctly with "*.txt" treated as a constant string and in all subsequent iterations unzip tries to unzip files with exactly the same filename (ie those files which were in the previous zip file).

for file in *.zip
do
    unzip ${file} *.txt
done

As an example, in the first loop it takes 1.zip and unzips e.g. file1.txt then it goes to the second loop, it takes 2.zip and tries to extract file1.txt again - instead choosing all the .txt files from 2.zip.

Was it helpful?

Solution

You need to protect your wildcard pattern with single quotes, otherwise the shell will expand it (this is called globbing):

for file in *.zip; do
    unzip ${file} '*.txt'
done

During the first iteration of the loop, *.txt doesn't expand to anything as there are no txt files in the working directory, so the command works as expected. After the first iteration, it expands to all the txt files you just extracted from the first zip file, so the second and subsequent iterations actually look something like this after globbing:

unzip ${file} file1.txt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top