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
How can I replace the last character of a string with another character in bash?
提问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 c
and replacing the last c
with s
.
例如:我把所有的文件结束c
和更换,最后c
用s
。
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 c
anchored to the right with s
.
使用参数替换。下面完成后缀替换。它将c
锚定到右侧的一个实例替换为s
。
for file in *.c; do
echo "${file/%c/s}"
done
回答by jkshah
Use rename
utility if you would want to get away with loop
rename
如果您想摆脱循环,请使用实用程序
rename -f 's/\.c$/.s/' *.c