【问题标题】:How to make grep not interpret special characters in my search string?如何使 grep 不解释我的搜索字符串中的特殊字符?
【发布时间】:2017-10-20 16:49:19
【问题描述】:

执行./test.sh 12.34 时,grep 应该匹配12.34 而不是12-34。这如何实现?

#!/bin/sh

ip=$1  
echo $ip
if netstat | grep ssh | grep $ip;  then
        netstat | grep ssh | grep $ip
else
        echo 'No'
fi

【问题讨论】:

    标签: bash grep escaping


    【解决方案1】:

    您可以将grep-F 选项一起使用:

    来自 man grep:

     -F, --fixed-strings
             Interpret pattern as a set of fixed strings (i.e. force grep to
             behave as fgrep).
    

    你的例子:

    grep -F "$ip"
    

    【讨论】:

    • 你应该引用"$ip",否则包含空格或全局字符的模式会导致有趣的惊喜。
    • @BenjaminW。你完全正确,我将其添加为编辑。
    【解决方案2】:

    grep 使用正则表达式匹配字符串。 . 是正则表达式中的特殊字符,所以需要转义。有一种相当优雅的方法:

    export escaped_ip_addr = $(echo $ip_addr | sed "s/\./\\\./g")
    

    这将是你的最终代码:

    #!/bin/sh
    
    #test.sh
    
    ip=$1
    echo $ip
    
    export escaped_ip = $(echo $ip | sed "s/\./\\\./g")
    if netstat | grep ssh | grep $escaped_ip;  then
            netstat | grep ssh | grep $escaped_ip
    else
            echo 'No'
    fi
    

    【讨论】:

    • 你试过了吗?您不能在 = 周围分配空格。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多