Print only if field is not empty
I have a text file that I want to pull host and IP info from only if the IP exists in column 4. For example:
cat hostlist.txt
Server One 255.255.255.255 123.123.123.123
Server Two 255.255.255.255
Server Three 255.255.255.255 123.123.123.123
In this case I would only want to see Server One and Three as Server Two has no data in the fourth column.
Solution 1:
awk '{if ($4) print $0;}' < hostlist.txt
does the trick. It's functionally equivalent to the earlier solution but is simpler since you only check for existence rather than matching a regex.
Solution 2:
If you can live with lines where field 4 has value 0
not being printed, you can simplify to
$ awk '$4' hostlists.txt
Server One 255.255.255.255 123.123.123.123
Server Three 255.255.255.255 123.123.123.123
This is functionally equivalent to {if ($4) print $0;}
, but reduced to just a pattern and using the default action of print $0
.
Solution 3:
awk approach:
awk 'NF>=4 && $4~/^([0-9]{1,3}\.){3}[0-9]{1,3}$/' hostlist.txt
The output:
Server One 255.255.255.255 123.123.123.123
Server Three 255.255.255.255 123.123.123.123
NF>=4
- ensures that a record has at least 4 fields
$4~/^([0-9]{1,3}\.){3}[0-9]{1,3}$/
- ensures that the 4th field contains IPv4 address (in most simple form. Real IPv4 validation requires an additional conditions)