Count pattern instances using grep

I'm trying to count / in a certain path, but grep counts all instances as 1 when it is in 1 line.

/home/usr/bin/test | grep / -c 

gives an answer 1.

4 Answers

Your command would actually count the number of lines containing / in the standard output of command /home/usr/bin/test

Here are some options to count the instances of / in the string /home/usr/bin/test:

grep -o '/' <<< "/home/usr/bin/test" | wc -l
tr -dc '/' <<< "/home/usr/bin/test" | wc -c
0

As grep -c counts number of lines that contain the pattern. Using the -o option outputs matched content on different lines. You can then use -c to count those lines.

grep -o '/' <<< "/home/usr/bin/test" | grep '/' -c

Using awk (Print each line separately):

awk -F"/" '{print NF-1}' my.txt
  • -F"/": consider / as field delimiters
  • NF-1: number of fields-1.

Print all lines:

tr -d '\n' < my.txt | awk -F"/" '{print NF-1}'

Using sed and grep:

sed "s@/@/\n@g" my.txt | grep -c /
  • sed "s@/@/\n@g" puts a new line after each / so grep can count all of them.

You're doing it wrong because:

  • -c flag counts number of matching lines
  • "/home/usr/bin/test | grep / -c is literally means that you're trying to execute /home/usr/bin/test file and pipe its output to grep

What you should be doing is this:

  • count individual output of grep with

    grep -o '/' <<< "/home/usr/bin/test" | wc -l 
  • use tools other than grep:

     # saving matches to array and printing array in scalar context $ perl -ne '@arr = $_ =~ /\//g;print 0+@arr' <<< "/home/usr/bin/test" 4 # building list of only / chars and getting length of that list $ python -c 'import sys; print(len([char for line in sys.stdin for char in line if char == "/"]))' <<< "/home/usr/bin/test" 4 # iterating over each character of string using substr $ awk '{for(i=1;i<=length($0);i++) if(substr($0,i,1)=="/") count++}END{print count}' <<< "/home/usr/bin/test" 4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like