I want to know the file count for a particular format like .txt in a particular directory
Asked
Active
Viewed 206 times
4 Answers
0
You can also use:
ls -l *.txt | wc -l

petry
- 978
-
2http://unix.stackexchange.com/questions/128985/why-not-parse-ls – Dmitry Grigoryev Oct 28 '15 at 09:23
-
-
1@MunaiDasUdasin
bash
doesn't glob dot-files unless you specifyshopt -s dotglob
, so no, it doesn't – Dmitry Grigoryev Oct 28 '15 at 09:46 -
@don_crissti of course you can parse the output of
ls
, or even useeval
properly. The point is, you often have simpler and more robust ways to do what you wanted. – Dmitry Grigoryev Oct 28 '15 at 11:58
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 charactertr -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