Count Occurrences of a String in a File
This page answers questions like these:
- How to count the number of lines in a file containing a string?
- How to count the number of lines in a file containing a pattern?
- How to count the number of times a string appears in a file?
- How to count the number of times a pattern appears in a file?
- How to count the number of times a string appears in a binary file?
- How to count the number of times a pattern appears in a binary file?
Related Links:
Count Occurrences of a Hexadecimal Sequence in a File
Count Number of Lines in a File Containing a String:
grep -c STRING FILE ...
- Count the number of lines in text file FILE which contain a STRING.
- Pros: Handles multiple files.
- Cons: Counts lines, not occurrences. Doesn’t handle binary files.
Count Number of Occurrences of a String in a File:
grep -o STRING FILE ... | wc -l
- Count the number of occurrences of string STRING in one or more text files.
- Pros: Handles multiple files. Counts actual occurrences. Fast.
- Cons: Doesn’t handle binary files.
- Caveats: The -o option to grep may not exist on all systems.
grep STRING FILE ... | sed 's/STRING/&\n/g' | grep -c STRING
- Count the number of occurrences of string STRING in one or more text files.
- Pros: Handles multiple files. Counts actual occurrences. Doesn’t rely on the -o option to grep.
- Cons: Doesn’t handle binary files. Slow.
Count Number of Occurrences of a String in a Binary File:
strings -a -n 1 FILE ... | sed 's/STRING/&\n/g' | grep -c STRING
- Count the number of occurrences of STRING in binary file FILE.
- Pros: Handles multiple files. Handles text and binary files. Counts actual occurrences.
- Cons: Slow, but faster if you change the 1 in the command to the length of the string STRING.
Related Links:
Count Occurrences of a Hexadecimal Sequence in a File
Home > Linux / Unix > Count Occurrences of a String in a File
Tags: count, string, pattern, file, text file, binary file, linux, unix, solaris, bsd, aix
Copyright © HelpDoco.com
file-count-string.txt
Linux-Unix/count-occurrences-of-string-in-file.htm
3