3

This question already has an answer here:

How can I recursively replace a string in all folders and files' name with a different string? I am running Red Hat 6 and I can find them with:

find . -name \*string\*

I've managed to do it for strings within files:

find . -type f -exec sed -i 's/string1/string2/g' {} +

but how could I replace in a similar way all file names?

marked as duplicate by ilkkachu, Archemar, roaima, Rui F Ribeiro, George Vasiliou Jan 11 '18 at 23:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • how can I replace a string with the mv command? There might be different folders names containing that string. I would need something like "find . -type f -exec sed -i 's/string1/string2/g' {} +" but for folder names – WooWapDaBug Jan 10 '18 at 9:34
  • On what operating system? Do you have a rename command? Is it perl rename? – terdon Jan 10 '18 at 9:35
  • mv is the final tool. You need to start with find + bash/shell beforehand – RomanPerekhrest Jan 10 '18 at 9:35
  • 1
    The command you show (sed) doesn't change any file names. It replaces the string inside the file but leaves the file name as it was. – terdon Jan 10 '18 at 9:37
  • @terdon I'm using red had 6, I have the rename command – WooWapDaBug Jan 10 '18 at 9:38
4

Using find and rename:

find . -type f -exec rename 's/string1/string2/g' {} +
  • This is nice! Please keep in mind that there are some cases with deeper direction structures. For flat directory changes this is fine. – gies0r Jan 15 at 12:24
2

you can replace all the file names using for and mv command.

here i am replacing all the text files starting with abc names with xyz

for file in abc*.txt; do mv -v "$file" "${file/abc/xyz}"; done

the below command will replace the files recursively in all folders

for file in `find . -type f -name 'abc*.txt'`; do mv -v "$file" "${file/abc/xyz}"; done
  • but this doesn't run recursively into folders, right? – WooWapDaBug Jan 10 '18 at 13:43
  • see the edited answer. – Ganesh_ Jan 11 '18 at 9:43
1

It's easier with zsh's zmv:

autoload zmv # best in ~/.zshrc
zmv '(**/)(*string1*)' '$1${2//string1/string2}'

Change to

zmv '(**/)(*string1*)(#qD)' '$1${2//string1/string2}'

If you also want to rename hidden files or files in hidden directories.

  • Oh, I didn't know that command. Unfortunately I can only use bash – WooWapDaBug Jan 10 '18 at 13:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.