How to search and replace text in a file
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Search and replace looks simple, but careless edits can break code, configuration, or data files quickly. A safe workflow includes preview, scoped matching, backups, and verification after changes. The right tool depends on whether you need a quick one-file edit, a scripted transformation, or regex-based rewriting across many files.
One-File Replacement with sed
For quick Unix-like shell edits, sed is fast and available almost everywhere.
Preview without modifying file:
Edit in place with backup:
Keeping .bak backups is useful when you are applying risky replacements under time pressure.
Scripted Replacement in Python
Python is better when you need encoding control, conditionals, and testable behavior.
This approach is explicit and easy to run in CI.
Regex Replacements for Structured Patterns
When the target varies, use regex carefully.
Anchor patterns tightly. Broad regex often overmatches and changes unrelated lines.
Multi-File Workflow with Preview
For repository-wide replacement, list candidate files first, then apply controlled edits.
Then run a scripted replacement only on that set. Avoid touching generated directories, build output, and lock files unless intentionally targeted.
Idempotent Replacement Scripts
A good replacement script is idempotent, meaning re-running it does not introduce new changes after first success. This makes reruns safe in CI and reduces merge conflicts during coordinated refactors.
Print changed paths in sorted order so review output is deterministic.
Validation After Replacement
Never treat replacement as complete until validated.
For config files, add environment-specific validation commands such as parser checks or service startup tests.
Encoding and Line Ending Concerns
Text replacements can unintentionally alter file encoding or line endings. If a repository mixes encodings or platform conventions, preserve original settings where possible. In Python, be explicit about encoding and avoid opening files in binary-unaware editor tools during scripted changes.
On cross-platform teams, verify that replacements did not create noisy line-ending diffs.
Rollback-Friendly Replacement Workflow
For high-risk edits, run replacements in a temporary branch and checkpoint frequently. A practical sequence is:
- Create a dedicated branch.
- Run replacement script in check mode.
- Apply write mode.
- Inspect diff and run tests.
- Commit only intended files.
This keeps rollback simple and prevents emergency fixes from mixing with unrelated changes.
Common Pitfalls
- Running in-place replacement without backup or version-control checkpoint.
- Using regex patterns that are too broad for the intended scope.
- Applying repository-wide replacement without exclusion rules.
- Ignoring file encoding and corrupting non-UTF text.
- Skipping post-change tests and committing broken results.
Summary
- Use
sedfor fast one-file changes and Python for safer scripted workflows. - Preview and scope replacements before writing changes.
- Keep regex patterns narrow and test-driven.
- Build idempotent replacement scripts for repeatable refactors.
- Validate with diffs and tests before merging.
Related reading
- How to seek for bigram similarity in gensim word2vec model
- How to serve a tensorflow-module, specifically Universal Sentence Encoder?
- How to set custom stop words for sklearn CountVectorizer?
- How to split text in a column into multiple rows
- How to split text without spaces into list of words
- How to strip all whitespace from string
- How to test SyntaxNet trained model Spanish UD?
- How to tie word embedding and softmax weights in keras?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.