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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19169175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:10:25  来源:igfitidea点击:

How can I replace the last character of a string with another character in bash?

stringbashshell

提问by user2709885

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.

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

For example: I am taking all the files that end in cand replacing the last cwith s.

例如:我把所有的文件结束c和更换,最后cs

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

Can someone please help me?

有人可以帮帮我吗?

回答by Henk Langeveld

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

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

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

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

以上删除了最后一个字符,并附加了“s”。

回答by iruvar

Use parameter substitution. The following accomplishes suffix replacement. It replaces one instance of canchored to the right with s.

使用参数替换。下面完成后缀替换。它将c锚定到右侧的一个实例替换为s

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

回答by jkshah

Use renameutility if you would want to get away with loop

rename如果您想摆脱循环,请使用实用程序

rename -f 's/\.c$/.s/' *.c