user5506560 user5506560 - 1 year ago 64
Linux Question

Put into file : index of line and total numbers of specific pattern

I'm trying to invent a command which add to the file index of line where numbers of commas are less than 5 + numbers of comma in line. Let's assume result:

Let's assume input:


So in first line there are 5 commas, in second - 6 and in third - 7
and the expected result:

Index: 2 Number of commas : 6
Index: 3 Number of commas : 7

I invented that command which put into errors.csv all contents of line if comma > 50.

awk -F , 'NF > 50' <filename.csv >> errors.csv

The hardest for me is - how to retrieve and put into file index of line ??
Could you support me?

Answer Source

You can get this expected output using NR and NF variables of awk:

awk -F"," '{ if(NF > 6) printf("Index: %d Number of commas : %d\n", NR, NF-1); }' filename.csv

NR gives you the number of records in a file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download