在bash脚本中按模式过滤行

时间:2009-11-21 20:00:05

标签: git bash sh

我有两个变量,一个是文本,另一个是模式。我想过滤掉线条,匹配的图案。我怎么能这样做?

我的脚本看起来像这样

# 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 个答案:

答案 0 :(得分:3)

您可以将模式文件直接提供给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

(我建议使用$()代替反引号。)


顺便说一句,这一行:

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

应该看起来像这样:

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

如果你要保留它。

答案 1 :(得分:0)

# 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