如何在bash中用另一个字符替换字符串的最后一个字符?

问题描述:

我正在使用bash编写一个小代码,但是我遇到了一个小问题.我有一个字符串,我想用 s 替换该字符串的最后一个字母.

I am working on a small code in bash, but I am stuck on a small problem. I have a string, and I want to replace the last letter of that string with s.

例如:我要提取所有以 c 结尾的文件,并用 s 替换最后一个 c .

For example: I am taking all the files that end in c and replacing the last c with s.

for file in *.c; do
   # replace c with s  
   echo $file

有人可以帮我吗?

for file in *.c; do 
   echo "${file%?}s"
done

在参数替换中,$ {VAR%PAT}将从变量VAR中删除与PAT匹配的最后一个字符.外壳模式 * ?可用作通配符.

In parameter substitution, ${VAR%PAT} will remove the last characters matching PAT from variable VAR. Shell patterns * and ? can be used as wildcards.

以上内容删除了最后一个字符,并附加了"s".

The above drops the final character, and appends "s".