代码之家  ›  专栏  ›  技术社区  ›  user1032531

如何使grep不解释搜索字符串中的特殊字符?

  •  3
  • user1032531  · 技术社区  · 7 年前

    执行时 ./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
    
    2 回复  |  直到 7 年前
        1
  •  9
  •   tobiasegli_te    7 年前

    你可以用 grep -F 选项:

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

    您的示例:

    grep -F "$ip"
    
        2
  •  0
  •   Derek Brown Onga Leo-Yoda Vellem    7 年前

    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