Question

Using avahi I have populated a list of ip-addresses on my network range. The information populated is then refined using sed to give the following output

Initial data = address = [xxx.xxx.xxx.xxx]
Refined data = xxx.xxx.xxx.xxx

The command to do so is as follows:

avahi-browse -alrt | grep -w address | sort -u | sed -e 's/address = //' | sed -e 's/\[//' | sed -e 's/\]//'

This works correctly most of the time however on the odd occasion addresses such as xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx are displayed in the list and I would like to omit them.

I know I could possibly use a regex expression or something to ensure the data always matches a valid ip i.e xxx.xxx.xxx.xxx but I am unsure as to how to go about this. Any help is much appreciated.

The command is run on linux using a bash script and I wish it to return only the valid ip addresses in the xxx.xxx.xxx.xxx format.

Was it helpful?

Solution

Replace your 3 sed commands with this one:

sed 's/address = \[\|\]//g' 

OR:

sed -r 's/address = \[|\]//g' 

EDIT: To remove invalid IPs also use this sed:

sed -r -e 's/address = \[|\]//g' -e 's/= +([^:]+\:){5,}.*$/=/' file

OTHER TIPS

Try replacing your three sed commands with following one

sed -nr 's/.*address = \[(([0-9]{1,3}\.){3}[0-9]{1,3})\].*/\1/p'
avahi-browse -alrt | sed -n "/address/ s/address = \[\(\([012]\{0,1\}[0-9]\{0,1\}[0-9]\.\)\{3\}[12]\{0,1\}[0-9]\{0,1\}[0-9]\)\].*/\1/p" | sort -u

sort could be done before but is certainly faster after the sed and grep is not needed because sed could also filter the lines. (not tested because not shell here)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top