4

i would like to know what's the best way to grep lines from text which have more than specific number of special characters.

Let's say that you already know that each line have 4 comma , and you would like to grep lines which have more than 4 comma ,

Example

hi,hello,how,are,you
catch,me,then,say,hello,then

Output

catch,me,then,say,hello,then
4

4 Answers 4

5

Perl solution:

perl -ne 'print if tr/,// > 4'
  • -n reads the file line by line
  • the tr operator returns the number of matches.

To print the lines with less than 4, just change > to <.

1
3

Using the grep command:

grep -E '(,.*){5}' myfile

does the job. Explanation:

-E: use an Extended Regex...

'(,.*): ... to find one comma followed by any number of characters, even zero...

{5}': ... and repeat the previous pattern 5 times.

If you want to grep lines with less than 4 commas, you'd need:

grep -xE '([^,]*,){0,3}[^,]*' myfile

This time, we need -x so the pattern is anchored at both start and end of the line so it matches the full line. And we use [^,]* instead of .* as the latter would otherwise happily match strings containing ,s as . matches any character.

Another approach is to reverse with -v the previous approach. "Fewer that 4" is the same as not "at least 4", so:

grep -vE '(,.*){4}' myfile
2

The awk version:

awk -F, 'NF > 5' myfile
-1

Achieved result by below one liner


l=`awk 'BEGIN{print }{print gsub(",","")}' example.txt |sed '/^$/d' |awk '$1 > 4 {print NR}'`;sed -n ''$l'p' example.txt  

output
catch,me,then,say,hello,then

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .