简体   繁体   English

通过一列中的匹配模式从文本文件中选择行

[英]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". 如果所有行的值均为零,则应收到类似“所有值均为零”的邮件警报。

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. 如果第二个字段不为0则条件为true-注意{print $0}awk的默认块,因此,如果这是您要执行的唯一操作,则可以将其忽略。

Regarding the mail alert, I think you'd better show some of your code to have a refer point. 关于邮件警报,我认为您最好显示一些代码以具有参考点。

Following awk should meet both of your requirements: 执行awk后,应该同时满足您的两个要求:

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. 您只需要用邮件发送命令替换print "all zeroes, send email"

Code for GNU : 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

为什么不Perl:

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

非常简单地使用awk,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有文本文件中的模式匹配的Scala RDD - Scala RDD with pattern matching from a text file Javascript:在HTML表格中,如何从一列中选择文本的一部分(与某些正则表达式匹配),然后将其移至下一列? - Javascript: in an HTML table, how to select part of text (matching some regex) from one column, and move it to the next one? 排除匹配模式中的一列 - Exclude one column in matching pattern 在CSV中选择与GNU Linux中的模式文件中的任何模式都不匹配的行(AWK / SED / GREP) - Select rows in a CSV not matching any pattern in pattern file in GNU Linux (AWK/SED/GREP) 文本文件规范化和模式匹配 - Text file normalization and pattern matching 在文本文件上多次匹配模式? - Matching pattern multiple times on text file? 如何在文本文件中进行多行模式匹配 - How to do multiline pattern matching in text file 匹配模式后从字符串中剪切文本 - Cutting text from string after matching pattern 在文本文件中的特定模式之后打印列 - printing a column after a specific pattern from a text file 从文本文件的特定列中提取正则表达式模式,然后执行减法 - Extract a regex pattern from a specific column of a text file then perform a subtraction
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM