Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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 ?

share|improve this question

2 Answers 2

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' {} +
share|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

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 '{}' \;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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