sed - How to extract IP address using sed?

前端 未结 5 2082
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-03 23:36

This is for an assignment so I have no choice but to use sed.

Given a file messages, how can I extract all the IP addresses and print them?

I first

5条回答
  •  旧时难觅i
    2021-01-04 00:20

    If you have GNU sed, you could simply add the -r flag to use EREs:

    sed -rn '/((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])/p' file
    

    Otherwise, you will need to escape certain characters:

    sed -n '/\(\(1\?[0-9][0-9]\?\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\(1\?[0-9][0-9]\?\|2[0-4][0-9]\|25[0-5]\)/p' file
    

    These characters include:

    • groups using parenthesis: (, )
    • occurrence braces: {, }
    • 'or' pipes: |
    • non-greedy question marks: ?

    Generally (although not for your case) I use the following to match IP address:

    sed -rn '/([0-9]{1,3}\.){3}[0-9]{1,3}/p' file
    

    Or in compatibility mode:

    sed -n '/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/p' file
    

提交回复
热议问题