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?
Solution 1:
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.
Solution 2:
find . -name "123*.txt" -exec rename 's/^123_//' {} ";"
will do it. No AWK, no for, no xargs needed, but rename, a very useful command from the Perl lib. It is not always included with Linux, but is easy to install from the repos.
Solution 3:
In case you want to replace string in file name called foo to bar you can use this in linux ubuntu, change file type for your needs
find -name "*foo*.filetype" -exec rename 's/foo/bar/' {} ";"