Issue
I have folders and files with the following structure and some of the files contains the string ModuleName
.
ModuleName
├── Application\ Logic
│ └── Interactor
│ ├── ModuleNameInteractor.swift
│ └── ModuleNameInteractorIO.swift
├── Module\ Interface
│ └── IModuleNameModule.swift
└── User\ Interface
├── Presenter
│ └── ModuleNamePresenter.swift
├── View
│ ├── IModuleNameView.swift
│ └── ModuleNameViewController.swift
└── Wireframe
└── ModuleNameWireframe.swift
I want to replace all the occurrences of ModuleName
in folder name, file name and file content by another name (let's say TestModule
) with a Linux or a python script.
I tried with the find
command but renaming the folders provoque No such file or directory
for the subfolders / subfiles.
Solution
I'd use sed -i
(in-place replace) for the content replacements, and a find|while read
loop for the renames.
Here's the BSD sed (standard on Macs) version:
find . -type f -exec sed -e s/ModuleName/TestModule/g -i '' '{}' ';'
find . -depth -name '*ModuleName*' -print0|while IFS= read -rd '' f; do mv -i "$f" "$(echo "$f"|sed -E 's/(.*)ModuleName/\1TestModule/')"; done
And here's GNU sed:
find . -type f -exec sed -e s/ModuleName/TestModule/g -i '{}' ';'
find . -depth -name '*ModuleName*' -print0|while IFS= read -rd '' f; do mv -i "$f" "$(echo "$f"|sed -r 's/(.*)ModuleName/\1TestModule/')"; done
The extra details in the while read
are to correctly handle arbitrary filenames -- names with spaces and other odd characters. Some quick testing suggests that zsh read
can now handle null-terminated strings properly; if you have issues, try running it in bash instead.
Answered By - Aaron Davies Answer Checked By - Clifford M. (WPSolving Volunteer)