Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace filename recursively in a directory

Tags:

find

bash

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?

like image 279
user1225606 Avatar asked Feb 22 '12 11:02

user1225606


People also ask

How do I find and replace a filename in a folder?

Select the files in Windows Explorer, hold Shift, and right-click them. Choose Copy as Path from the menu. Paste the list into whatever editor you prefer. You get the full pathname for each file, but a simple find/replace will clean that up if necessary.

How do I replace a filename in bulk?

Type the following command to rename the part of the file name and press Enter: ren OLD-FILE-NAME-PART*. * NEW-FILENAME-PART*. * In the command, replace "OLD-FILE-NAME-PART" and "NEW-FILENAME-PART" with the old and new parts of the filename.


1 Answers

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.

like image 110
sorpigal Avatar answered Sep 19 '22 17:09

sorpigal