Unix Command to return all files that end with single digit and TXT extension

fileslswildcards

Which command returns all files that end with a single digit and have the TXT extension ?

Best Answer

One of the most basic tools for locating files (or other kinds of nodes) is the find utility.

find ./ -type f -name '*[!0-9][0-9].txt'

This will search:

  • ...recursivly from the current directory (./). You could change this to another path or even leave it off since this is the default value for most versions of find.
  • ...for items that are files as opposed to directories, devices nodes, symbolic links, etc (-type f). You could leave this off if you wanted to find other types too.
  • ...for items that match the name pattern given. Note that I have used single quotes to encose the pattern so that bash or your shell does not try to expland it to a glob pattern before find even gets the command. The star matches any number of characters, then the end of the file must be something other than a digit, then a digit, then your extention. (-name '*[0-9].txt')

If there are files whose name is only a digit followed by .txt, the command above will miss them, because it requires one non-digit before the digit. The following equivalent commands use boolean operators to include file names with just a digit as well (-o is “or” and ! is “not”):

find ./ -type f \( -name '*[!0-9][0-9].txt' -o -name '[0-9].txt' \)
find ./ -type f -name '*[0-9].txt' ! -name '*[0-9][0-9].txt'

Note that this will be case sensitive. If you would like an insensitive match, you can use -iname instead of -name to match things like file4.TXT as well. Also be aware that just because a file claims to be a text file with that extention does not mean it is. On linux any file can be any type no matter the name. There might also be text files with other extentions or with no extention at all.