Those are just two of the many ways to manipulate strings in Bash. In this case, both serve to remove a snippet from the end of a string.
The difference is that %
removes as little as possible, while %%
removes as much as possible. For example, if I have:
texto='abcdefbxyz'
And make:
echo ${texto%b*z}
It will remove the smallest snippet of the end of the string that corresponds to b*z
(the letter b
, zero or more characters and the letter z
). The shortest stretch that satisfies this condition is bxyz
, therefore result of this echo
is abcdef
.
Now if I do:
echo ${texto%%b*z}
It will remove the longest stretch of the end of the string that corresponds to b*z
(the letter b
, zero or more characters and the letter z
). The longest stretch that satisfies this condition is bcdefbxyz
, therefore result of this echo
is a
.
In your case, the string is "Este texto para teste."
. In doing echo ${x% *}
, it removes the smallest snippet of the end of the string that corresponds to a space followed by zero or more characters. The snippet that satisfies this condition is teste.
, so the result is Este texto para
.
And what to do echo ${x%% *}
, it removes the longest stretch of the end of the string that corresponds to a space followed by zero or more characters. The snippet that satisfies this condition is texto para teste.
, so the result is Este
.
It’s a very useful resource (for any situation that involves removing a final chunk of a string), far from being something "just for exercises".
In the documentation has some examples.
Thanks! Great synthesis, when reading the second line I have already understood!
– Luiz Augusto