Andrey Baulin
Andrey Baulin

Reputation: 679

bash read file line by line and use lines as arguments

I have a file 'list' with a list of archives that I want to unpack. My script is:

#!/bin/bash
while read line
do
   echo 'string has been read'
   grep -e '**.zip' | xargs -d '\n' unzip -o
done < 'list'

But it works only for first zip-archive in a list and ignores other strings in list. If I comment out the 'grep -e '**.zip' | xargs -d '\n' unzip -o' script reads all lines.

I can't understand why it works this way, and how to fix it.

Upvotes: 1

Views: 1206

Answers (2)

jgr
jgr

Reputation: 3974

You're not refering to $line in your loop. Hence it wont work the way you want.

What about:

#!/bin/bash
while read line; do
    if [[ "$line" =~ "\.zip$" ]]; then
        unzip -o $line
    fi
done < list

Upvotes: 1

Pat
Pat

Reputation: 1766

Could be done even without a loop, I think.

grep '\.zip$' < yourfile.txt | xargs -n1 unzip -o

or, from stdin:

grep '\.zip$' | xargs -n1 unzip -o

The -n1 tells xargs to use 1 command line per argument

Upvotes: 3

Related Questions