tags:

views:

252

answers:

2

Hello! I have two variables, one with text, and another with patterns. And I want to filter out lines, matched patterns. How can I do that?

My script looks like this

# get ignore files list
IGNORE=`cat ignore.txt`

# get changed files list
CHANGED=`git diff --name-only $LAST_COMMIT HEAD`

# remove files, that should be ignored from change list
for IG in $IGNORE; do
    echo $CHANGED
    $CHANGED=`cat $CHANGED | grep -v $IG`
done
+2  A: 

You can supply the pattern file directly to grep

# get changed files list and remove files that should be ignored
CHANGED=$(git diff --name-only $LAST_COMMIT HEAD | grep -vf ignore.txt)
echo $CHANGED

(I recommend using $() instead of backticks.)


By the way, this line:

$CHANGED=`cat $CHANGED | grep -v $IG`

should probably look like this:

CHANGED=`echo $CHANGED | grep -v $IG`

if you were going to keep it.

Dennis Williamson
Yes, thanks. It's good idea for supply the pattern file directly to grep.
AlexLocust
A: 
# Disable globbing
set -f
# Collect variables
IGNORE=$(cat ignore.txt)
CHANGED=$(...)

# Apply each pattern in turn
for pattern in $IGNORE
do
    # Reset the current list of candidates
    CANDIDATES=
    for candidate in $CHANGED
    do
        # Apply the pattern
        CANDIDATES="$CANDIDATES ${candidate%$pattern}"
    done
    # Update the CHANGED list
    CHANGED=$CANDIDATES
done
Tom
In order to avoid spawning a process, you can do `IGNORE=$(< ignore.txt)`
Dennis Williamson