2

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

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

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 or more.

If you want to grep lines with less than 4 commas, replace {5,}' with {0,3}'.

1

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

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.