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"
-
%(shortest match from end)echo ${FULL_PATH/%*.txt/}(Removes.2023.txt)- Result:
/home/user/documents/report
Here,
*.txtmatches the shortest possible string ending in.txt. In this case,.2023.txtis removed. -
%%(longest match from end)echo ${FULL_PATH/%%*.txt/}(Removesuser/documents/report.2023.txt)- Result:
/home/
Here,
*.txtmatches the longest possible string ending in.txt. Because*is greedy, it matches everything fromuser/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.txtThis 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!