Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter lines by pattern in bash script

Tags:

git

bash

sh

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
like image 593
AlexLocust Avatar asked Dec 29 '25 02:12

AlexLocust


1 Answers

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.

like image 187
Dennis Williamson Avatar answered Dec 31 '25 19:12

Dennis Williamson