• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 388
  • Last Modified:

How to count the number of a particular string in a file?

I wonder how to count the number of appearances of a particular string in a file? grep -c  can only find the number of lines that contain the string.
Another question is how to substitue a non-printable character into a return
 character "\n" using sed?  The following command seems doesn't work.
#top -d 1 >f1
#sed "1,$ s/\033/\012/g" f1
Why?   Here \033 stands for ASCII code 033 which displays as ^[ (non-printable),
\012 is "carriage return".
0
shiqi
Asked:
shiqi
1 Solution
 
ozoCommented:
perl -ne 'BEGIN{$/="string"} END{print $.-1,"\n"}' f1
perl -pe 's/033/\012/g' f1
0
 
mdchachiCommented:
non-perl answers:

1)
cat somefile | sed -n ' :LOOP
         /string/ {
                  p
                  s/string//
                  b LOOP
        } ' | grep -c string

2) not sure about sed, what about tr?

cat file | tr  '\033'  '\012'
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now