Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

bash - Find and replace filename recursively in a directory

I want to rename all the files in a folder which starts with 123_xxx.txt to xxx.txt.

For example, my directory has:

123_xxx.txt
123_yyy.txt
123_zzz.txt

I want to rename all files as:

xxx.txt
yyy.txt
zzz.txt

I have seen some useful bash scripts in this forum but I'm still confused how to use it for my requirement.

Let us suppose I use:

for file in `find -name '123_*.txt'` ; do mv $file {?.txt} ; done

Is this the correct way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it this way:

find . -name '123_*.txt' -type f -exec sh -c '
for f; do
    mv "$f" "${f%/*}/${f##*/123_}"
done' sh {} +

No pipes, no reads, no chance of breaking on malformed filenames, no non-standard tools or features.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...