-1

I want to know the file count for a particular format like .txt in a particular directory

4 Answers4

2

You can do, from that directory:

files=( *.txt )
echo "${#files[@]}"
heemayl
  • 56,300
0

You can also use:

ls -l *.txt | wc -l
petry
  • 978
0

A portable approach, which also handles strange filenames (for example with newlines in it), dot-files (filename starts with a .) and other special characters like quotes (only the current directory):

find -maxdepth 1 -type f -iname "*.txt" -print0 | tr -cd '\0' | wc -c

Or recursively (without -maxdepth), will count files in subdirectories too:

find -type f -iname "*.txt" -print0 | tr -cd '\0' | wc -c

Explanation:

  • -maxdepth 1 search inly in the current directory, don't descend into subdirectories.
  • -type f search only regular files.
  • -iname "*.txt" search for files with ending txt case-insensitive.
  • -print0 this is the important part, delimit the list by the null byte character
  • tr -cd '\0' removes everything except the null byte character.
  • wc -c counts the number of characters (which is now the number of files)
chaos
  • 48,171
0

You can do in this way:

ls /path/to/directory | grep ".txt$" | wc -l

If you want search to include subdirectories:

ls -lR /path/to/directory | grep ".txt$" | wc -l

Other way is:

find . -name "*.txt" | wc -l
serenesat
  • 1,326