Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print only if field is not empty

Tags:

grep

bash

awk

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.

like image 789
teamg Avatar asked May 04 '17 19:05

teamg


3 Answers

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.

like image 198
Kyle Banerjee Avatar answered Oct 21 '22 10:10

Kyle Banerjee


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.

like image 30
Benjamin W. Avatar answered Oct 21 '22 09:10

Benjamin W.


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)

like image 24
RomanPerekhrest Avatar answered Oct 21 '22 10:10

RomanPerekhrest