echo output with % and %

Asked

Viewed 126 times

4

When solving some exercises in Shell Script, I find this script:

x="Este texto para teste."
echo ${x% *}

I confess that, when performing the table test, I could not solve it. When running this script the result was:

Este texto para

However if you modify echo to echo ${x%% *}, the result will be:

Este

What is the explanation for these results, both with % as to %%? Is there any practical use in these expressions or their emphasis is only on teaching exercises?

1 answer

2


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.

  • 1

    Thanks! Great synthesis, when reading the second line I have already understood!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.