1

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.

5
  • sorry I meant ls *.tx that would work Commented Feb 9, 2016 at 22:18
  • how would I use it in this case? Commented Feb 9, 2016 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? Commented Feb 9, 2016 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 Commented Feb 9, 2016 at 22:31
  • why not just do ls *.tx *.txt? Commented Aug 28, 2020 at 23:43

1 Answer 1

4

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.

3
  • is there a way to do it without the shopt -s extglob Commented Feb 9, 2016 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) Commented Aug 29, 2020 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). Commented Aug 29, 2020 at 6:03

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.