Using sed to search and replace an ip address in a file

前端 未结 4 1096

Been trying to get this working for a while and not really quite getting it. Basically, I have a file with an ip address that changes more or less on a daily basis. The file

相关标签:
4条回答
  • 2020-12-10 16:58
    IP=207.0.0.2; [[ x${IP}x =~ x"(2([0-4][0-9])|2(5[0-5])|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(2([0-4][0-9])|2(5[0-5])|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(2([0-4][0-9])|2(5[0-5])|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(2([0-4][0-9])|2(5[0-5])|1[0-9][0-9]|[1-9][0-9]|[0-9])"x ]] && echo ok || echo bad
    

    this validates only four decimal octet representation so this one will fail 016.067.006.200 (even valid but not four decimal octet representation, but octal)

    016.067.006.200 =~ 14.55.6.200
    
    0 讨论(0)
  • 2020-12-10 17:05

    Try this:

    sed -e 's/ \(\([0-9]\{1,3\}\.\)\{1,3\}\).[0-9]/NEW_IP/g'
    
    0 讨论(0)
  • 2020-12-10 17:08

    If your version of sed supports extended regular expressions (the -r option), you could do something like this (which is similar to what you have in your grep statement). Also note $newip is outside the single quotes to allow the shell to replace it.

    sed -r 's/(\b[0-9]{1,3}\.){3}[0-9]{1,3}\b'/"$newip"/
    

    BTW this solution still matches strings that do not represent IP addresses. See this site under IP Adresses for more complex solutions.

    0 讨论(0)
  • 2020-12-10 17:10
    sed -e 's/old ip/new ip/g' filename
    
    0 讨论(0)
提交回复
热议问题