Hot answers tagged


Another POSIX one: awk -F , 'NF == 11' <file If the line has 10 commas, then there will be 11 fields in this line. So we simply make awk use , as the field delimiter. If the number of fields is 11, the condition NF == 11 is true, awk then performs the default action print $0.


Using egrep (or grep -E in POSIX): egrep "^([^,]*,){10}[^,]*$" file.csv This filters out anything not containing 10 commas: it matches full lines (^ at the start and $ at the end), containing exactly ten repetitions ({10}) of the sequence "any number of characters except ',', followed by a single ','" (([^,]*,)), followed again by any number of characters ...


The simplest grep code that will work: grep -xE '([^,]*,){10}[^,]*' Explanation: -x ensures that the pattern must match the entire line, rather than just part of it. This is important so you don't match lines with more than 10 commas. -E means "extended regex", which makes for less backslash-escaping in your regex. Parentheses are used for grouping, ...


Throwing some short python: #!/usr/bin/env python2 with open('file.csv') as f: print '\n'.join(line for line in f if line.count(',') == 10) This will read each line and check if the number of commas in the line is equal to 10 line.count(',') == 10, if so print it will the line.


And here's a Perl way: perl -F, -ane 'print if $#F==10' The -n causes perl to read its input file line by line and execute the script given by -e on each line. The -a turns on automatic splitting: each input line will be split on the value given by -F (here, a comma) and saved as the array @F. The $#F (or, more generally $#array), is the highest index ...


If fields can contain commas or newlines your code needs to understand csv. Example (with three columns): $ cat filter.csv a,b,c d,"e,f",g 1,2,3,4 one,two,"three ...continued" $ cat filter.csv | python3 -c 'import sys, csv > csv.writer(sys.stdout).writerows( > row for row in csv.reader(sys.stdin) if len(row) == 3) > ' a,b,c d,"e,f",g ...

Only top voted, non community-wiki answers of a minimum length are eligible