Can `?` and `[]` be combined?

QuestionsQuestions8 SkillsProDec, 10 2025
068

Yes, absolutely! You can combine ? and [] (and *) in the same wildcard pattern.

Combining them allows for even more specific and powerful matching. For example:

Let's imagine you have a directory with these files:

  • doc_01.txt
  • doc_A1.txt
  • document_01.txt
  • doc_X9.txt
  • report_01.txt

If you wanted to match files that start with doc_, followed by any single character that is either a digit (0-9) or 'X', and then another single character, and end with .txt, you could use:

ls doc_?[0-9X].txt

Let's break this down:

  • doc_?: Matches files starting with doc_ followed by any single character (like doc_0, doc_A, doc_X).
  • [0-9X]: This ensures the character after the ? is either a digit (0-9) OR the letter 'X'.
  • .txt: The file must end with .txt.

In our example, ls doc_?[0-9X].txt would match:

  • doc_A1.txt (the ? matches A, [0-9X] matches 1)
  • doc_X9.txt (the ? matches X, [0-9X] matches 9)

It would not match:

  • doc_01.txt (because after doc_, the ? matches 0, but then the next character is 1, which is matched by [0-9X] so the pattern doc_?[0-9X].txt would actually be doc_ + any_char + any_char_from_set)
    Wait, I might have made a mistake in the example description. Let me correct that specific case for clarity.

Let's use a simpler, clearer example.

Suppose you have files:

  • file_A1.log
  • file_B2.log
  • file_AX.log
  • file_C3.log
  • other_file.log

If you wanted to match files that start with file_, have any single character in the third position, followed by a character that is either 1 or X, and end in .log:

ls file_?[1X].log

This would match:

  • file_A1.log (the ? matches A, [1X] matches 1)
  • file_AX.log (the ? matches A, [1X] matches X)

It would not match:

  • file_B2.log (because [1X] does not match 2)
  • file_C3.log (because [1X] does not match 3)
  • other_file.log (because it doesn't start with file_)

Does this example clarify how ? and [] can be combined? Feel free to ask if you want to explore more combinations!

0 Comments

no data
Be the first to share your comment!