9

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?

4

3 回答 3

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

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

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

于 2013-10-03T21:06:02.397 回答
4

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

for file in *.c; do
   echo "${file/%c/s}"  
done
于 2013-10-03T21:06:47.233 回答
0

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

rename -f 's/\.c$/.s/' *.c
于 2013-10-03T21:14:26.433 回答