简体   繁体   English

Bash AWK 和正则表达式应用于特定列

[英]Bash AWK and Regex Apply on specific Column

I have the following dataset我有以下数据集

Name,quantity,unit
car,6,6
plane,7,5
ship,2,3.44
bike,8,7.66

I want to print only the names which has unit in whole numbers.我只想打印具有整数单位的名称。

I have done the following which does not give out the result我做了以下没有给出结果

#!/bin/bash
awk 'BEGIN {
 FS=","
}
/^[0-9]*$/ {
 print "Has Whole numbers: " $1
} 
' file.csv

The result should be结果应该是

Has Whole numbers: car
Has Whole numbers: plane

Added a couple of lines to your test data:在您的测试数据中添加了几行:

Name,quantity,unit
car,6,6
plane,7,5
ship,2,3.44
bike,8,7.66
Starship,1,1.0
Super Heavy,2,0
null,0,

And awk:和 awk:

$ awk -F, 'int($3)==$3 ""' file

Output: Output:

car,6,6
plane,7,5
Super Heavy,2,0

int($3) makes an integer of $3 and $3 "" turns $3 to a string. int($3)使 $ $3的 integer 和$3 ""$3变成一个字符串。

Try changing /^[0-9]*$/ to $3 ~ /^[0-9]*$/ && $3 != 0 once in your tried attempt it should work then.尝试在您的尝试中将/^[0-9]*$/更改为$3 ~ /^[0-9]*$/ && $3 != 0一次它应该可以工作。

In case you DO NOT want to hard code field number and want to find out unit field number automatically then try following.如果您不想硬编码字段编号并想自动找出单位字段编号,请尝试以下操作。

awk -F="," -v field_val="unit"  '
FNR==1{
  for(j=1;j<=NF;j++){
    if($j==field_val){
       field_number=j
       next
    }
  }
}
$field_number ~ /[0-9]*$/ && $field_number!=0{
    print "Has whole numbers: " $1
}'  Input_file

If you are sure 3rd column is a number:如果您确定第三列是一个数字:

awk -F, '(NR != 1 && $3 !~ /\./){print "Has Whole numbers:", $1}' file.csv

or well actually its better the way you did it:或者实际上它的方式更好:

awk -F, '$3 ~ /^[0-9]$/{print "Has Whole numbers:", $1}' file

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM