How does `%` differ from `%%`?

QuestionsQuestions8 SkillsProDec, 14 2025
0125

That's an excellent follow-up question! It shows you're really digging into the details of Bash string manipulation.

You're referring to pattern removal or substring deletion operations in Bash, which are similar in syntax but different in how much they remove.

Here's the difference between % and %% (and for completeness, # and ##):

Value Deletion

These operations delete a pattern from the beginning or end of a string.

Operator Description
% Deletes the shortest match of pattern from the end of string.
%% Deletes the longest match of pattern from the end of string.
# Deletes the shortest match of pattern from the beginning of string.
## Deletes the longest match of pattern from the beginning of string.

Let's look at an example to make % and %% clear:

Suppose you have a file path: FULL_PATH="/home/user/documents/report.2023.txt"

  1. % (shortest match from end)

    • echo ${FULL_PATH/%*.txt/} (Removes .2023.txt)
    • Result: /home/user/documents/report

    Here, *.txt matches the shortest possible string ending in .txt. In this case, .2023.txt is removed.

  2. %% (longest match from end)

    • echo ${FULL_PATH/%%*.txt/} (Removes user/documents/report.2023.txt)
    • Result: /home/

    Here, *.txt matches the longest possible string ending in .txt. Because * is greedy, it matches everything from user/ onwards, as long as it still ends with .txt.

    Another common example for %% is extracting just the filename without the full path:
    echo ${FULL_PATH##*/} (Removes the longest match of */ from the beginning)
    Result: report.2023.txt

    This is not a % vs %% example, but rather # vs ##.


Coming back to your original question about string replacement (which uses /):

The difference between / and // in replacement syntax is similar:

  • /: Replaces only the first occurrence of the pattern.
    Example: ${STRING/old/new}
  • //: Replaces all occurrences of the pattern.
    Example: ${STRING//old/new}

So, while % and %% are used for removing parts of a string from the end, the single / and double // are used for replacing parts of a string.

You're doing great in understanding these powerful Bash features! Keep exploring!

0 Comments

no data
Be the first to share your comment!