1753366 Members
5709 Online
108792 Solutions
New Discussion юеВ

While Read a File

 
SOLVED
Go to solution
Bob Ferro
Regular Advisor

While Read a File

I have a simple one. I have a script with the following lines:



cat email_list | while read L
do
mailx -s "Test Data" $L < /dev/null
done



The email_list is a file with various email address, one line per email address. Let's say I have 10 entries and I want to comment out one line with an "#". Now when my script runs, I want to send an email out to 9 people instead of 10. I want to comment out the address rather than delete it. How can I set up my "while read" instruction to bypass any lines with an "#" in it?
4 REPLIES 4
Pete Randall
Outstanding Contributor
Solution

Re: While Read a File

Bob,

For my simple mind, the following works:

for L in `cat email_list |grep -v '#'`
do
mailx -s "Test Data" $L < /dev/null
done


Pete

Pete
Bob Ferro
Regular Advisor

Re: While Read a File

Bam!

Pete, it worked like a charm. Thanks again.
James R. Ferguson
Acclaimed Contributor

Re: While Read a File

Hi Bob:

One simple way:

# cat ./mailer
#!/usr/bin/sh
while read X L
do
[ ${X} = "#" ] && continue
mailx -s "Test Data" ${L} < /dev/null

done < email_list

If your file has a "#" field as the first field of the line it will be skipped.

Notice, too that your can eliminate the 'cat' process. The loop reads your file directly.

Regards!

...JRF...




blah2blah
Frequent Advisor

Re: While Read a File

i cant beleive you guys missed the details.

Pete, you know the # should be at the begining of the line and therefore your grep should be anchored to the begining of the line: grep -v "^\#"

and James, your solutions assumes there is always a space after the #, as in:
# thisworks
#thisdoesn't

and you improve performance by eliminating the cat, but still run mailx for each address

something like this would be better,
comments can be at the end of the line,
as in:
addr # to me

will work and it creates a variable of the addresses and runs mailx just once

addrs=""
while read myAddr
do
myAddr=${myAddr%%#.*} #remove first # and everything on the line after it
myAddr=${myAddr%%#} #remove # if it is last character on the line or only character
addrs="${addrs} ${myAddr}"
done < email_list

mailx -s sub $addrs