Search code examples
linuxbashawkcut

Extract IPs before string


I have this text:

111.11.1.111(*)222.22.2.221(mgn)333.33.3.333(srv)
111.11.1.111(*)333.33.3.333(srv)222.22.2.222(mgn)
222.22.2.223(mgn)111.11.1.111(*)333.33.3.333(srv)

I only want to know the IP's before (mgn), output:

222.22.2.221
222.22.2.222
222.22.2.223

thanks


Solution

  • Through grep,

    $ grep -oP '(?:\d{1,3}\.){3}\d{1,3}(?=\(mgn\))' file
    222.22.2.221
    222.22.2.222
    222.22.2.223
    

    Through sed,

    $ sed 's/.*\b\(\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\)(mgn).*/\1/g' file
    222.22.2.221
    222.22.2.222
    222.22.2.223