Re: Piping within for-loops
From: Ed Morton (morton_at_lsupcaemnt.com)
Date: 02/27/05
- Previous message: Ed Morton: "Re: sed problem"
- In reply to: Barry Margolin: "Re: Piping within for-loops"
- Next in thread: John W. Krahn: "Re: Piping within for-loops"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 27 Feb 2005 09:35:07 -0600
Barry Margolin wrote:
> In article <d756f1c9.0502270452.2f902ef@posting.google.com>,
> halsbrecherisch@yahoo.com (halsbrecherisch) wrote:
>
>
>>Hi!
>>I want to write a script, that selects words from a wordlist,
>>which don't contain certain characters, e.g.
>># ./filter a b c
>>lists all words that don't contain the letters a, b and c.
>>I've written this script:
>>
>>--- begin
>> cat /usr/share/dict/words |
>>
>> for omit in $1
>> do
>> if [ ! "$omit" == "" ]; then grep -v -i "$omit" ; else cat; fi
>> done |
>>
>> tee result
>>--end
>>
>>My problem is, that the grep only affects the piped data during the 1st
>>loop of the for statement. How can I solve this?
>
>
> Unless you run the script like:
>
> ./filter "a b c"
>
> it looks to me like your script will only loop once anyway. Don't you
> mean:
>
> for omit in "$@"
>
> ?
>
> Anyway, if you want to reread the file each time through the loop, put
> the file reading inside the loop:
>
> DICT=/usr/share/dict/words
> for omit in "$@"
> do
> if [ ! "$omit" == "" ]
I realise you're just mimicing the OPs logic, but don't test negatives
unnecessarily. Any time you find yourself using a "!", think long and
hard about whether or not you could express the condition in a positive
way. It makes future mauintenance much easier. In this case, this code
could be written:
if [ "$omit" == "" ]
then cat "$DICT"
else grep -v -i "$omit" "$DICT"
fi
> then grep -v -i "$omit" $DICT
> else cat $DICT
> fi
> done | tee result
The above logic will print most of the words from the file multiple
times. The only words you won't see will be those that contain all of
the letters to be skipped.
To see just the words that contain none of the letters, and to only see
each word once, do this:
DICT=/usr/share/dict/words
omit=`echo "$*" | tr -d ' '`
if [ -n "$omit" ]
then grep -v -i "[$omit]" "$DICT" | tee result
else cat "$DICT" | tee result
fi
Depending on which shell you use, you could improve on the above, but
that should work in any bourne-like shell.
Ed.
- Previous message: Ed Morton: "Re: sed problem"
- In reply to: Barry Margolin: "Re: Piping within for-loops"
- Next in thread: John W. Krahn: "Re: Piping within for-loops"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|