Given a directory "Centos1" which has few files named Centos1.x, Centos1.y, Centos1.z and these files also has "Centos1" in their contents. Using a single command ( using find, sed, perl -pie ) how can I get them renamed to "Centos2" for all occurence of "Centos1" Here are the content of Centos1 directory.

Centos1.nvram      Centos1-s005.vmdk  Centos1.vmsd  vmware-2.log
Centos1-s001.vmdk  Centos1-s006.vmdk  Centos1.vmx   vmware.log
Centos1-s002.vmdk  Centos1-s007.vmdk  Centos1.vmxf
Centos1-s003.vmdk  Centos1-s008.vmdk  vmware-0.log
Centos1-s004.vmdk  Centos1.vmdk       vmware-1.log

NOTE: I want to have "Centos1" replaced with "Centos2" inside all files too if it's present.

I ran the below mentioned command after I changed to "Centos1" directory

find . -type f -exec sed -i 's/Centos1/Centos2/g' {} +

But it didn't help. Any input ?

link|improve this question
feedback

2 Answers

up vote 1 down vote accepted

You can use the rename command to do the renaming

rename Centos1 Centos2 *

or if you have the perl rename

rename 's/Centos1/Centos2' *

Your find command should change all occurences of Centos1 to Centos2 so you could wrap them in a simple script to make it a single command.

#!/bin/bash
rename Centos1 Centos2 *

find . -type f -exec sed -i 's/Centos1/Centos2/g' {} +
link|improve this answer
But has is this "rename" command the perl one or util-linux package one ? – Ashutosh Narayan Jul 27 '11 at 13:23
@AshutoshNarayan: On the CentOS system I tested on it's a binary. I just checked an Ubuntu system which has the perl script. I've updated my answer to take that into account. – Iain Jul 27 '11 at 14:07
Yes, it worked for me. Thanks ! – Ashutosh Narayan Jul 29 '11 at 7:47
feedback

Does your answer really need to include only these commands, or can you use bash builtins and file globbing?

for file in Centos1*; do
  sed -i 's/Centos1/Centos2/g' "$file"
  mv "$file" "$(echo "$file" | sed 's/^Centos1/Centos2/')"
done

Edit: Using just find/sed, and renames inside files

find ./ -type f -name Centos1* -exec sh -c 'sed -i "s/Centos1/Centos2/g" "$1"; mv "$1" "$(echo "$1" | sed "s/Centos1/Centos2/")"' X '{}' \;
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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