Linux – How to use sed, perl to rename files and its contents with a particular pattern in a given directory

findlinuxperlsed

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 ?

Best Answer

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