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
  • grep -E '(.*,){5}' file? Commented Dec 22, 2017 at 10:04
  • @Cyrus thank you and in case if you wanna grep what is less than 4 ? Commented Dec 22, 2017 at 10:06
  • also go ahead and write your comment as answer so i gonna accept it as answer. Commented Dec 22, 2017 at 10:07
  • grep -E '^([^,]*,){,3}[^,]*$' file? This might help: The Stack Overflow Regular Expressions FAQ Commented Dec 22, 2017 at 10:19

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
  • That's brilliant solution which i highly like . Commented Dec 22, 2017 at 10:11
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.