Vignesh
Vignesh

Reputation: 259

Select rows from a text file by a matching pattern in one column

I have a file in the following format.

Table_name Value
Employee   0
student    50
Payroll    0
animals    20

I need to fetch the entire row in which the value is non-zero.

The expected output would be

student    50
animals    20

If the value is zero for all the rows, I should get a mail alert like "all values are zero".

Upvotes: 0

Views: 744

Answers (5)

captcha
captcha

Reputation: 3756

Code for GNU :

$sed '/\S+\s+[0]+\b/d' file
Table_name Value
student    50
animals    20
$sed -r '/\S+\s+([1-9]|[0]+[1-9])/!d' file
student    50
animals    20

Upvotes: 2

Mariappan Subramanian
Mariappan Subramanian

Reputation: 10083

Very simply with awk,

awk -F " " '{if($2 > 0) print $0}' your_file

Upvotes: 1

Vijay
Vijay

Reputation: 67319

why not perl:

perl -ane 'print if($.!=1 && $F[1]!=0)' your_file

Upvotes: 1

anubhava
anubhava

Reputation: 786289

Following awk should meet both of your requirements:

awk 'NR>1 && $2 {nz=1;print}; END{if (!nz) print "all zeroes, send email"}' file
  • You just need to replace print "all zeroes, send email" with your mail sending command.

Upvotes: 2

fedorqui
fedorqui

Reputation: 290515

This can work:

$ awk '$2' file
Table_name Value
student    50
animals    20

If the 2th field is not 0 then the condition is evaluated as true - note that {print $0} is the default block in awk so it can be omitted if this is the only action you want to perform.

Regarding the mail alert, I think you'd better show some of your code to have a refer point.

Upvotes: 2

Related Questions