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 delimitersNF-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/sogrepcan count all of them.
You're doing it wrong because:
-cflag counts number of matching lines"/home/usr/bin/test | grep / -cis literally means that you're trying to execute/home/usr/bin/testfile and pipe its output togrep
What you should be doing is this:
count individual output of
grepwithgrep -o '/' <<< "/home/usr/bin/test" | wc -luse 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