Using Ubuntu Commands to Replace Words
When working on development projects, you may encounter scenarios where you need to replace a specific word or string (e.g., abc) with another (e.g., xyz) across files, file names, and folder names. Manually making these changes can be time-consuming and error-prone. This article explains how you can do this using simple commands in Ubuntu.
Replace Text Inside Files
To replace occurrences of a specific word or string in the content of all files recursively, you can use the sed command:
Replace Words in File Names
To replace abc with xyz in file names, use the rename command:
Replace Words in Folder Names
Renaming directories containing abc is slightly more complex. Use the following script:
Combine All Commands
To apply all three replacements (in folder names, file names, and file content), you can combine the commands:
Explanation of Commands
Content Replacement (sed)
- sed -i 's/abc/xyz/g': Replaces all occurrences of abc with xyz in the content of files.
- Find /path/to/root/folder -type f: Searches for all files.
File Name Replacement
- rename 's/abc/xyz/': Changes file names containing abc to xyz.
Folder Name Replacement
- find ... -type d | while read dir: Iterates through all directories containing abc.
- mv "$dir": Renames each directory by replacing abc with xyz.
By using these commands, you can save time and effort when replacing words across files, file names, and folders. Whether you’re updating a codebase, refactoring a project, or simply standardising naming conventions, these automation techniques are invaluable.
Need more development tips?
Stay tuned to our blog.