regex

  • The IP Address

    This particular page (and actually the rest of the pages on this site) is designed to save me time when I forget how to compose a specific regular expression. IP addresses are one of those constantly annoying regex to craft from scratch, but my good buddy @r3dc3ll tends to be a regex ninja who is also handy with Sed and Awk and he recently imparted to me the following. So if you need to extract ONLY the IP addresses from some file where pipes and spaces are the delimiters then the following BASH command will do the trick:

    cat some_file|awk -F “|” ’{print $2"\n"$3}’ |sed -e ’s/ //g’|sed -e ’s/*//g’

    and of course if you only want unique IP addresses that are sorted you can append some or all of sort & uniq which might give you:

    cat some_file|awk -F “|” ’{print $2"\n"$3}’ |sed -e ’s/ //g’|sed -e ’s/*//g’|sort | uniq

    If spaces are the only delimiter then this should work:

    cat some_file|awk ’{print $2}’ |sed -e ’s/ //g’

    If you need a simple IP address matching string then this works where Grep uses matching PERL expressions:

    cat some_file | grep -P ’\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}’ > some_output_file

    This is useful when you need to match an IP address and extract the entire row (line) from the file.

    Happy parsing!