When working on large codebases, renaming variables, updating URLs, or replacing deprecated functions manually is inefficient. The solution? Use Linux’s powerful command-line tools like grep, sed, and find to automate the process.
In this guide, you’ll learn how to:
- Find matching strings using
grep - Replace them using
sed - Combine them for batch updates in entire codebases
This is a must-have skill for developers, sysadmins, and DevOps engineers working in Unix/Linux environments.
🔍 Step 1: Grep to Find the Target String
To search for a string in your codebase:
grep -rnw './' -e 'oldFunctionName'
Explanation:
-r: recursive-n: show line number-w: match whole word'./': search in current directory-e: pattern to search
✅ This will list all occurrences of 'oldFunctionName'.
✏️ Step 2: Replace the String Using sed
Here’s the basic structure:
sed -i 's/oldString/newString/g' filename
Flags:
-i: in-place edits: substituteg: global (replace all in line)
🔁 To test without changing the file, remove the -i flag.
🤖 Step 3: Grep + Find + Sed (Mass Replace in Codebase)
To recursively find and replace in all files:
find ./ -type f -name "*.c" -exec sed -i 's/oldFunction/newFunction/g' {} +
Use cases:
- Replace function names in
.cfiles - Update class names in .java files
- Rename components in
.js,.ts,.htmletc.
💡 Replace "*.c" with "*" to search all file types.
🔐 Safety Tip: Backup Before Replacing
To back up files before editing:
sed -i.bak 's/old/new/g' filename
Creates a filename.bak with original content.
📦 Optional: Preview Changes Before Applying
To preview files to be changed:
grep -rl 'oldString' ./ | xargs grep 'oldString'
To apply changes after confirmation:
grep -rl 'oldString' ./ | xargs sed -i 's/oldString/newString/g'
✅ Useful when you want to manually inspect changes before applying them.
⚙️ Common Examples
| Task | Command Example |
|---|---|
Replace text in all .js files | find . -name "*.js" -exec sed -i 's/foo/bar/g' {} + |
| Find case-insensitive match | grep -rin 'text' . |
Replace text only in files under src | find ./src -type f -exec sed -i 's/text/replace/g' {} + |
| Replace with word boundaries only | sed -i 's/\<old\>/new/g' file |
Using Linux commands to grep and replace text across source code is a game-changing productivity hack. Whether you’re refactoring a project or fixing typos in bulk, this method is faster, safer, and more scalable than any manual approach.
Don’t forget to:
- Always back up before mass replacement
- Test your
sedcommand without-ifirst - Use regular expressions for powerful pattern matching
Did you try these commands in your project?
Let us know your use case in the comments—and share any clever one-liners you use! 💻👇
