Why does the following bash string removal not work for me?

时间:2015-09-01 22:55:09

标签: bash

s=abcdefg
echo ${s%c}

I expect the output to be ab, but abcdefg is printed.

I'm on bash 4.30

2 个答案:

答案 0 :(得分:2)

${s%c} removes the shortest suffix matching the pattern. Your pattern is "c".

It looks like you want ${s%c*}:

$ s=abcdefg; echo ${s%c*}
ab

See more in the bash manual's section on Shell Parameter Expansion (3.5.3).

答案 1 :(得分:1)

The notation that you are using only removes when the pattern (after the %) matches at the end of the string.

s=abcdefg
echo ${s%c}

result: abcdefg

echo ${s%efg}

result: abcd

To get the behavior you were expected add a *

echo ${s%c*}

result: ab