Question

Let's say I have a bunch of files and one of them has .txt as the extension and others have .x.txt where x could be whatever. How do I pull out the file that only has the .txt extension ?

Here's a reproducible example:

touch file.txt file.x.txt
echo *.txt
# file.txt file.x.txt
Was it helpful?

Solution

% touch file.txt file.x.txt
% echo [^.]#.txt 
file.txt

From the FILENAME GENERATION section of man zshexpn:

   [...]  Matches any of the enclosed characters.  Ranges of characters can be specified by separating two characters by a `-'.  A `-' or `]' may be matched by including it as  the  first  character  in  the
          list.   There  are also several named classes of characters, in the form `[:name:]' with the following meanings.  The first set use the macros provided by the operating system to test for the given
          character combinations, including any modifications due to local language settings, see ctype(3):

   ...

   [^...]
   [!...] Like [...], except that it matches any character which is not in the given set.

   ...

   x#     (Requires  EXTENDED_GLOB to be set.)  Matches zero or more occurrences of the pattern x.  This operator has high precedence; `12#' is equivalent to `1(2#)', rather than `(12)#'.  It is an error for
          an unquoted `#' to follow something which cannot be repeated; this includes an empty string, a pattern already followed by `##', or parentheses  when  part  of  a  KSH_GLOB  pattern  (for  example,
          `!(foo)#' is invalid and must be replaced by `*(!(foo))').

So this matches any string ending with .txt that contains no other . characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top