Quantcast
Channel: Count the occurrences of a string in a file - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 4

Answer by Kusalananda for Count the occurrences of a string in a file

$
0
0
$ grep -c '\.java$' file
3

The -c flag to grep will make it report the number of lines in the input that matches the pattern.

The pattern \.java$ will match any line that ends with .java.

$ name="file"
$ printf 'Total number of Java files in "%s":\t%d\n' "$name" "$( grep -c -- '\.java$' "$name" )"
Total number of Java files in "file":   3

Or even just (with GNU grep or compatible):

$ grep -Hc '\.java$' file
file:3

Or (still with GNU grep):

$ grep --label='Total java files in "file"' -Hc '\.java$' < file
Total java files in "file":3

Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>