在 bash 脚本中按模式过滤行

发布于 2024-08-12 12:33:41 字数 366 浏览 6 评论 0原文

我有两个变量,一个包含文本,另一个包含模式。我想过滤掉线条、匹配的图案。我怎样才能做到这一点?

我的脚本看起来像这样

# 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

絕版丫頭 2024-08-19 12:33:41

您可以直接向 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`

如果您要保留它。

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.

所谓喜欢 2024-08-19 12:33:41
# 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
# 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文