I'm suppose to write a command that would list all files that end in .tx with an optional t at the end.

So far all I got is listing the files that end in .tx which is:

ls *.tx

Now my problem is how do I add the optional t at the end.

  • sorry I meant ls *.tx that would work – shawn edward Feb 9 '16 at 22:18
  • how would I use it in this case? – shawn edward Feb 9 '16 at 22:22
  • What do you expect in here? To list files ending in .tx and .txt or really want to know if an "optional" character can be attached? – tachomi Feb 9 '16 at 22:27
  • @tachomi like I already under how to show files ending in .tx but what command will list files that end in .tx with an optional t at the end – shawn edward Feb 9 '16 at 22:31
  • why not just do ls *.tx *.txt? – user56452 Aug 28 '20 at 23:43

In bash with shopt -s extglob you can do this:

ls -d *.tx?(t)

In bash with shopt -s nullglob you can do this:

ls -d *.txt *.tx

But this will show the directory content if no such file exists.

If ls is not required:

find . -type f '(' -name '*.txt' -o -name '*.tx' ')'

This would show files in subdirectories, too. With GNU find this can be avoided with find . -maxdepth 1.

  • is there a way to do it without the shopt -s extglob – shawn edward Feb 9 '16 at 22:36
  • 1
    (1) The first two commands can be improved by the addition of the -d option.  As written now, if you have a directory called dir.tx, then either of those commands will list the contents of dir.tx in addition to listing the text files.  -d will prevent that.  (2) -d will help the second command in another way.  Currently, if it is executed in a directory where there are no text (.txt or .tx) files, it will list all the files in the current directory.  With -d, it will just say .. … (Cont’d) – G-Man Says 'Reinstate Monica' Aug 29 '20 at 6:03
  • (Cont’d) …  (3) In the spirit of the first command, the find command can be shortened to find . -type f -regex '.*\.txt?' (assuming GNU find). – G-Man Says 'Reinstate Monica' Aug 29 '20 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.