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?
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".
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
如果您想要使用循环,请使用rename
实用程序
rename -f 's/\.c$/.s/' *.c
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.