Bash Script: sed/awk/regex to match an IP address and replace

15,545

Solution 1

Replace a fixed IP address with a host name:

$ cat log | sed -r 's/10\.224\.0\.2/example.com/g'

Replace all IP addresses with a host name:

$ cat log | sed -r 's/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/example.com/g'

If you want to call an external program, it's easy to do that using Perl (just replace host with your lookup tool):

$ cat log | perl -pe 's/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/`host \1`/ge'

Hopefully this is enough to get you started.

Solution 2

There's variou ways to find th IP addresses, here's one. Just replace "printf '<<<%s>>>' " with "host" or whatever your command name is in this GNU awk script:

$ cat tst.awk
{
    subIp = gensub(/\/.*$/,"","",$4)
    srcIp = gensub(/.*\[Source: ([^]]+)\].*/,"\\1","")

    "printf '<<<%s>>>' " subIp | getline subName
    "printf '<<<%s>>>' " srcIp | getline srcName

    gsub(subIp,subName)
    gsub(srcIp,srcName)

    print
}
$
$ gawk -f tst.awk file
Oct 24 12:37:45 <<<10.224.0.2>>>/<<<10.224.0.2>>> 14671: Oct 24 2012 12:37:44.583 BST: %SEC_LOGIN-4-LOGIN_FAILED: Login failed [user: root] [Source: <<<10.224.0.58>>>] [localport: 22] [Reason: Login Authentication Failed] at 12:37:44 BST Wed Oct 24 2012
Share:
15,545
jwbensley
Author by

jwbensley

Senior network engineer / architect Programmer Hobbyist hardware hacker/tinkerer

Updated on June 05, 2022

Comments

  • jwbensley
    jwbensley almost 2 years

    I have a string in a bash script that contains a line of a log entry such as this:

    Oct 24 12:37:45 10.224.0.2/10.224.0.2 14671: Oct 24 2012 12:37:44.583 BST: %SEC_LOGIN-4-LOGIN_FAILED: Login failed [user: root] [Source: 10.224.0.58] [localport: 22] [Reason: Login Authentication Failed] at 12:37:44 BST Wed Oct 24 2012
    

    To clarify; the first IP listed there "10.224.0.2" was the machine the submitted this log entry, of a failed login attempt. Someone tried to log in, and failed, from the machine at the 2nd IP address in the log entry, "10.224.0.58".

    I wish to replace the first occurrence of the IP address "10.224.0.2" with the host name of that machine, as you can see presently is is "IPADDRESS/IPADDRESS" which is useless having the same info twice. So here, I would like to grep (or similar) out the first IP and then pass it to something like the host command to get the reverse host and replace it in the log output.

    I would like to repeat this for the 2nd IP "10.224.0.58". I would like to find this IP and also replace it with the host name.

    It's not just those two specific IP address though, any IP address. So I want to search for 4 integers between 1 and 3, separated by 3 full stops '.'

    Is regex the way forward here, or is that over complicating the issue?

    Many thanks.