How can I replace the last character of a string w

2019-06-16 10:46发布

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.

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

Can someone please help me?

3条回答
够拽才男人
2楼-- · 2019-06-16 11:23
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.

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

查看更多
家丑人穷心不美
3楼-- · 2019-06-16 11:27

Use rename utility if you would want to get away with loop

rename -f 's/\.c$/.s/' *.c
查看更多
在下西门庆
4楼-- · 2019-06-16 11:29

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

for file in *.c; do
   echo "${file/%c/s}"  
done
查看更多
登录 后发表回答