Parse ifconfig to get only my IP address using Bash

后端 未结 20 1209
甜味超标
甜味超标 2020-11-30 05:04

I want to edit the bashrc file to have a simple function called \"myip\" to run. As you might guess, the function myip prints only my internal IP address of my machine.

20条回答
  •  [愿得一人]
    2020-11-30 05:41

    Taking patch's answer, making it a bit more general,

    i.e.: skipping everything till the first digit.

    ifconfig eth0 | awk '/inet addr/{sub(/[^0-9]*/,""); print $1}'

    Or even better:

    ifconfig eth0 | awk '/inet /{sub(/[^0-9]*/,""); print $1}'

    • Please note the print part at the end - changes from $2 to $1.

    Using Perl Regex:

    ifconfig eth0 | grep -oP '(?<= inet addr:)[^ ]+'

    Explanation: grep -oP searches for an EXACT match using Perl regex.
    The "tricky" part is the regex itself;
    1. (?<= inet addr:) means - that the string inet addr: is to the LEFT of what we're looking for.
    2. [^ ]+ (please notice the space after the ^ ) - it means to look for everything until the first blank - in our case it is the IP Address.

提交回复
热议问题