在bash变量中使用通配符处理echo和grep

问题描述 投票:1回答:1

我正在尝试提供一个功能,该功能可以在给定文件中搜索给定模式。如果找不到该模式,则应将其附加到文件中。

这在某些情况下可以正常工作,但是当我的模式包含特殊字符(例如通配符(*))时,此方法将失败。

有效的模式:pattern="some normal string"

无效的模式:pattern='#include "/path/to/dir/\*.conf"'

这是我的功能:

check_pattern() {
    if ! grep -q "$1" $2
    then
        echo $1 >> $2
    fi
}

我这样调用我的函数:check_pattern $pattern $target_file

在我的模式变量中转义通配符以使grep正确运行时,echo\解释为字符。

因此,当我第二次运行脚本时,我的grep找不到该模式并再次附加它。

简单地说:附加的资料:#include "/path/to/dir/\*.conf"

我想附加的东西:#include "/path/to/dir/*.conf"

是否有某种方法可以在不将我的echo模式存储在第二个变量中的情况下获得期望的结果?

bash grep echo
1个回答
0
投票

谢谢,我明白了。

使用Gem Taylor指出的grep -F并结合像这样的check_pattern "$pattern" "$target_file"来调用我的函数就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.