How to Replace a Word in Files, File Names, and Folder Names on Ubuntu

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:

find /path/to/root/folder -type f -exec sed -i 's/abc/xyz/g' {} +

Replace Words in File Names

To replace abc with xyz in file names, use the rename command:

find /path/to/root/folder -type f -name "*abc*" -exec rename 's/abc/xyz/' {} +

Replace Words in Folder Names

Renaming directories containing abc is slightly more complex. Use the following script:

find /path/to/root/folder -type d -name "*abc*" | while read dir; do
mv "$dir" "$(echo $dir | sed 's/abc/xyz/g')"
done

Combine All Commands

To apply all three replacements (in folder names, file names, and file content), you can combine the commands:

# Replace content inside files
find /path/to/root/folder -type f -exec sed -i 's/abc/xyz/g' {} +
# Replace file names find /path/to/root/folder -type f -name "*abc*" -exec rename 's/abc/xyz/' {} +
# Replace folder names find /path/to/root/folder -type d -name "*abc*" | while read dir; do mv "$dir" "$(echo $dir | sed 's/abc/xyz/g')" done
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.

Dharmesh Patel 13 December, 2024
Archive
Sign in to leave a comment
How to Automate Old Backup Deletion