[英]How can I replace the last character of a string with another character in bash?
I am working on a small code in bash, but I am stuck on a small problem. 我正在使用bash中的一个小代码,但我遇到了一个小问题。 I have a string, and I want to replace the last letter of that string with
s
. 我有一个字符串,我想用
s
替换该字符串的最后一个字母。
For example: I am taking all the files that end in c
and replacing the last c
with s
. 例如:我正在获取以
c
结尾的所有文件,并用s
替换最后一个c
。
for file in *.c; do
# replace c with s
echo $file
Can someone please help me? 有人可以帮帮我吗?
for file in *.c; do
echo "${file%?}s"
done
In parameter substitution, ${VAR%PAT} will remove the last characters matching PAT from variable VAR. 在参数替换中,$ {VAR%PAT}将从变量VAR中删除与PAT匹配的最后一个字符。 Shell patterns
*
and ?
壳型
*
和?
can be used as wildcards. 可以用作通配符。
The above drops the final character, and appends "s". 上面删除了最后一个字符,并附加“s”。
Use parameter substitution . 使用参数替换 。 The following accomplishes suffix replacement.
以下完成后缀替换。 It replaces one instance of
c
anchored to the right with s
. 它用
s
替换了一个锚定在右边的c
实例。
for file in *.c; do
echo "${file/%c/s}"
done
如果您想要使用循环,请使用rename
实用程序
rename -f 's/\.c$/.s/' *.c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.