Home > Net >  How to print field count is greater than 3
How to print field count is greater than 3

Time:08-27

I want to print CSV whose field count is greater than 3.

For example, CSV is below,

aaa,bbb
aaa,bbb,ccc
aaa,bbb,ccc,ddd
aaa,bbb,ccc,ddd,eee

expectation is

aaa,bbb,ccc,ddd
aaa,bbb,ccc,ddd,eee

I tried the command, but it failed. Is there a way to solve this problem?

awk -F, 'BEGIN{OFS=“,”}{$NF>=5;print}' aaa.csv
awk -F',' '{$NR>=5;print }' aaa.csv

CodePudding user response:

Simply check NF is greater than 3

awk -F',' 'NF>3{print $0}' aaa.csv

OR since awk's default behavior is to print lines(as an action) when no action is given so above could be shorten to:

awk -F',' 'NF>3' aaa.csv

CodePudding user response:

This

awk -F, 'BEGIN{OFS=“,”}{$NF>=5;print}' aaa.csv
awk -F',' '{$NR>=5;print }' aaa.csv

suggest you are misunderstanding certain features of GNU AWK.

$ is used to denote field (of row), NF is number of fields in current line, NR is number of current row. Thus $NF denotes value of last field and $NR denotes 1st field of 1st row, 2nd field of 2nd row, 3rd field of 3rd row and so on.

When you put ;-sheared action inside { and } they will be executed in such order, but your comparisons have not any side effect, so they are effectively no-operation.

print (without argument) does print line as-is, so setting OFS has not any effect at it.

If you want to know more about built-in variables then read 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR.

  • Related