Shell – the Linux command to display how many file names in the directory end in two digits

fileslsshellwildcards

What is the Linux command to display how many file names in the directory end in two digits?
Using ls with a command like this :

ls -l | wc –l  *[0-9][0-9]

Best Answer

In Bash, the following works non-recursively. You can of course put it in a function:

shopt -q nullglob || restore=1 && shopt -s nullglob
var=(*[0-9][0-9])
echo ${#var[@]}
[ 1 -eq "$restore" ] && shopt -u nullglob

That works even if you have crazy file names. If your file names are not crazy, then you can use that ls approach:

ls -d1b *[0-9][0-9] | wc -l

Note that the flags I used to ls are different: -d will make list the directory, not its contents (if you had a directory named something00 for example); -1 says to use a single column for output; -b escapes file names, which will make most crazy file names work.

Both of those will include the directory named something00 in the count. If you need just files, or recursion, find is what you're looking for. This will search the current directory (.), recursively, for files (-type f) only:

find . -type f -name '*[0-9][0-9]' -printf 'f\n' | wc -l

Note the use of -printf, to print just the letter f instead of the file name. You only want to count them, this way its immune to crazy file names.

Related Question