简体   繁体   English

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

[英]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.

相关问题 如何用 Python 中的另一个字符替换字符串中的一个字符? - How do I replace a character in a string with another character in Python? 如何用 Python 中的另一个字符替换字符串中一个字符的随机 5 个实例? - How can I replace random 5 instances of a character in a string with another character in Python? 如何用随机字符替换字符串中间的字符? - How can I replace a character in of the middle of a string with a random character? 我可以用另一个字符串替换一个字符串中的某个字符吗? - Can I replace a certain character in a string with another string? 如何用VB6替换字符串中的最后一个字符? - How do I replace the last character in a string with VB6? 如何检查最后一个字符串字符是否等于 Bash 中的“*”? - How to check if the last string character equals '*' in Bash? 如何获得以两个字符之一结尾的字符串,并用regexp有条件地替换最后一个字符? - How can I get a string that finishes with one of two characters and replace that last character conditionally by regexp? 如何仅替换一个字符和字符串的最后一个 - How to replace only one character, and the last of the string Java如何将字符串的最后一个字符替换为特定字符 - Java how to replace last character of string to specific character 在 Bash 中用另一个字符替换一个字符 - Replace one character with another in Bash
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM