2

We have csv file with more than 50000 lines This is only example

Dcccrev,wefrwvfr,rfregt,wr4f,rfvrv,ecxwec,ecfrv,rfrf
Grge,gtgr,frfrv,gthtgv,gerg5tgvrt,rvrfvtg,tgt,frfrf,rfrf
Drfrfr,t,tgtg,rf,rgr,grtg,tgt,gtgtg,rg
.
.
.

My task is: in case numbers of separator “,” In each line isn’t equal to 7 then need to print the line number

Is it possible to create one awk line or one perl liner for this task?

Without to use echo or cat that spend time

5

This is fairly easy with awk. You can set the delimiter to , with -F',' then count the columns with NF. For 7 comma's we would need 8 fields and print the current line number with NR.

awk -F ',' 'NF != 8 {print NR}' test.txt

Contents of test.txt

Dcccrev,wefrwvfr,rfregt,wr4f,rfvrv,ecxwec,ecfrv,rfrf
Grge,gtgr,frfrv,gthtgv,gerg5tgvrt,rvrfvtg,tgt,frfrf,rfrf
Drfrfr,t,tgtg,rf,rgr,grtg,tgt,gtgtg,rg

Output

2
3
  • 1
    can be golfed to 'NF != 8 { print NR}' – Archemar Feb 28 '17 at 14:50
  • you can try awk -F ',' 'NF != 8 {print NR,NF}' test.txt get output like 2 8 \n 3 8 – Pengju Zhao May 29 at 12:25
2

Perl's s/// operator(could also have used the tr/// aka y/// as well) returns the number of substitutions it performed which can be used to find the number of ",". Similarly, the m// operator returns the number of matches.

perl -lne 's/,//g == 7 or print $.'      yourfile
perl -lne 'print $. if 7 != (() = /,/g)' yourfile
sed   -ne 's/[^,]//g; /^.\{7\}$/!='      yourfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.