1755847 Members
4532 Online
108838 Solutions
New Discussion юеВ

Re: elif loop help

 
SOLVED
Go to solution
lawrenzo_1
Super Advisor

elif loop help

Hello all,

I am trying to list files in a directory and if they are *.Z then uncompress or if they are *.gz then gunzip however the sytax I run will uncompress the *.Z files but error on the *.gz files, here is my syntax:

for COMPRESSED in `awk '{print $1}' list`
do
if [ -f *.Z ] ; then
echo "uncompressing $COMPRESSED"
uncompress $COMPRESSED
elif [ -f *.gz ] ; then
echo "uncompressing gzipped $COMPRESSED"
gunzip $COMPRESSED
else
continue
fi
done

any help would be greatly appreciated or another solution?

Please note that there thousands of files and running 2 find commands would put additional load to the server.

Thanks

Chris.
hello
8 REPLIES 8
Dennis Handly
Acclaimed Contributor
Solution

Re: elif loop help

You shouldn't be using awk. And you need pattern matching in your ifs:
for COMPRESSED in $(< list); do

if [[ $COMPRESSED = *.Z ]]; then
...
elif [[ $COMPRESSED = *.gz ]]; then
...
fi
done
Dennis Handly
Acclaimed Contributor

Re: elif loop help

>Me: You shouldn't be using awk.

Oops, that assumes you only have filename in your file "list" and not other columns you want to ignore.
lawrenzo_1
Super Advisor

Re: elif loop help

Thanks Dennis,

yes the list file has 3 fields so awk would work however I will try you example with the while loop ie:

while read FILE DATE YEAR
do
if [[ FILE = *.Z ]] ; then
etc
etc
done < list

will let you know how I get on

cheers

Chris
hello
lawrenzo_1
Super Advisor

Re: elif loop help

again thankyou

works a treat and picked up something new:

for files in $(etc
etc.

Chris.
hello
Hemmetter
Esteemed Contributor

Re: elif loop help

Hi Chris,

if think you want to test $COMPRESSED
either [ -f $COMPRESSED ]
if $COMPRESSED is the filename including the postfix .Z (.gz)
or [ -f ${COMPRESSED}.Z ]
if $COMPRESSED does not have the .Z



rgds
HGH


Dennis Handly
Acclaimed Contributor

Re: elif loop help

If you have lots of pattern matching, you can use a case:
for COMPRESSED in ...; do
case $COMPRESSED in
*.Z) echo "uncompressing $COMPRESSED"
;;
*.gz|*.tgz) echo "uncompressing gzipped $COMPRESSED"
;;
*) echo "not one of those guys"
;;
esac
done

I used "|" above to allow both patterns.
lawrenzo_1
Super Advisor

Re: elif loop help

ok nice one,

I like that as it appears to be very effiecient.

Thanks
hello
lawrenzo_1
Super Advisor

Re: elif loop help

ty
hello