subdiox
subdiox

Reputation: 387

Find files and replace the part of the name of them in Bash

I know how to look for files that includes characters and put the extension after the names of the files.
For example,
find . -name "name1*" -exec mv {} {}.bak

After executing this code,
name111 name11 kname1 name2 name3
will be
name111.bak name11.bak kname1 name2 name3.

However, I would like to know how to replace the part of the file name.
For example, I would like to replace
name111 name11 kname1 name2 name3
with
name222 name22 kname2 name2 name3

In this case, I looked for files that include 1 and replaced 1 with 2.

My environment is OS X 10.10 Public Beta 5.
Sorry for my bad English.

Upvotes: 0

Views: 93

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

You can do something like this:

find . -name "name1*" -type f -exec sh -c 'mv "{}" "$(echo "{}" | tr 1 2)"' \;

please test it in some files that you have backed up!

That finds the files you want and then executes sh on each of them. Inside the shell script, it uses mv to rename the file from its original name to its name with all the 1s transliterated into 2s.

The above will maybe not do what you want if you have a file called name1 in a directory called /something1or2/with/another/1/in/it because it will replace the 1s in the directory path too - but maybe you don't have that!

Upvotes: 2

Related Questions