Using awk
would be the preferred way. Nice one liner. But just to show another solution:
#!/bin/bash
COUNTER=0
IP=
COMPANY=
nmap -sP 192.168.1.* | while read line
do
if [[ "$line" =~ ^Nmap ]]; then
IP=$(echo "$line" | sed -e "s/.*(\(.*\))/\1/")
fi
if [[ "$line" =~ ^MAC ]]; then
COMPANY=$(echo "$line" | sed -e "s/.*(\(.*\))/\1/")
COUNTER=$((COUNTER+1))
echo "${COUNTER}. ${COMPANY} (${IP})"
IP=
COMPANY=
fi
done
Explanation of sed commands:
The first sed command extracts the IP Address from the lines with the format Nmap scan report for macbook.att.net (192.168.1.21)
. The sed command uses a somewhat simple regex (I should have also used anchors and character classes to be sure I was extracting an IP) with a capture group. The first part of the sed command (between the first and second /
) is string to be matched, .*(\(.*\))
. The .*(
matches any (or no characters) followed by an open parenthesis. The capture group is next, this is \(.*\)
which captures any number of characters (in a production environment this should change to a regex that matches the format of an IP Address). The end of the complete regex is a single )
. The second part of the sed command (between the second and third /
) is what the regex gets replaced with. In this case, just \1
which indicates whatever was in the first capture group.
The second sed command is basically the same thing, which is to say "match the string that contains a set of parenthesis at the end, replace the whole string with what was inside the parenthesis.
What is tricky is that when you are not using the flag to use extended regular expressions, the (
and )
are literal. Open and close parenthesis. They need to be escaped, \(
and \)
, to indicate they are being used for grouping.
Lastly the -e
option I use in the command. In this case it's optional since each sed command only has one script/regex to match. It's a habit of mine to always use it.
Suggested reading, man pages regex(3)
, regex(7)
which is sometimes referred to as re_format(7)
, and the O'Reilly book "Mastering Regular Expressions" by Jeffrey Friedl.