How to Grep and Replace Strings in Source Code via Linux Command Line (Fast & Easy)

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:

✅ 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 edit
  • s: substitute
  • g: 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 "*.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

TaskCommand Example
Replace text in all .js filesfind . -name "*.js" -exec sed -i 's/foo/bar/g' {} +
Find case-insensitive matchgrep -rin 'text' .
Replace text only in files under srcfind ./src -type f -exec sed -i 's/text/replace/g' {} +
Replace with word boundaries onlysed -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 sed command without -i first
  • 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! 💻👇

Leave a Comment