Find and replace string in a file using 'sed' or 'awk'

Abstract: Replace all occurrences of a specific string in a file using sed or awk with in-place editing and proper escaping.

Created: 2026-09-30 by

To find and replace a string in a file using Linux, use the sed command with the -i flag for in-place editing. The basic syntax is sed -i 's/old_string/new_string/g' filename.txt. This command searches for old_string and replaces all occurrences with new_string directly within the specified file.

Using sed for Simple Substitutions

The sed (Stream Editor) utility is the most common tool for text substitution in Unix-like systems. It processes input streams and can modify files without creating temporary backups if configured correctly. The core operation relies on the substitute command, which follows the pattern s/pattern/replacement/flags. To perform a global replacement, ensuring every instance of the target string is changed rather than just the first one per line, append the g flag. For example, to replace all instances of "error" with "warning" in a log file named app.log, you would run:
sed -i 's/error/warning/g' app.log
The -i option instructs sed to edit files in place. Without this flag, sed outputs the modified content to standard output, allowing you to pipe it into a new file or view it in the terminal. In-place editing modifies the original file, so it is crucial to understand that any data loss is immediate. If you wish to create a backup before modifying the file, you can provide an extension to the -i flag, such as -i.bak. This creates a copy of the original file with the .bak suffix before applying changes. For more complex scenarios involving regular expressions, sed supports extended regex with the -E flag. This allows for more flexible pattern matching, such as replacing dates in various formats. However, for simple string replacements, basic regex is sufficient and often safer to avoid unintended matches.

Handling Special Characters and Escaping

One of the most frequent pitfalls when using sed involves special characters in the search or replacement strings. The delimiter used in the substitute command (typically /) must not appear in the string being searched or replaced unless it is escaped. If your strings contain slashes, such as file paths like /usr/bin, you should either escape them or choose a different delimiter. Using a different delimiter, such as | or #, can simplify commands dealing with paths. For instance:
sed -i 's|/old/path|/new/path|g' config.yaml
This approach eliminates the need to backslash-escape each slash, making the command cleaner and less error-prone. Additionally, if the replacement string contains characters that sed interprets specially, such as & (which refers to the matched pattern) or \, these must be escaped with a backslash. For example, to replace a string with the literal text "test&value", you must write test\&value in the replacement part of the command. Understanding how sed handles these characters prevents subtle bugs where parts of the original text are unexpectedly retained or duplicated in the output. Always test your sed commands on a copy of the file or without the -i flag first to verify the output matches expectations.

Using awk for Advanced Text Processing

While sed excels at line-by-line substitutions, awk offers a more powerful framework for text processing, particularly when you need to manipulate fields or perform conditional logic during replacement. awk treats input as records separated by delimiters, making it ideal for structured data like CSV or TSV files. To replace a specific field in a comma-separated file, you can use awk with the -F option to set the field separator. For example, to change the second column of a CSV file from "old" to "new":
awk -F',' '{if ($2 == "old") $2 = "new"; print}' OFS=',' file.csv > temp.csv && mv temp.csv file.csv
Note that awk does not support in-place editing natively in all versions, so redirecting output to a temporary file and then moving it back is a common workflow. This method ensures data integrity by writing the entire processed file atomically. You can also combine multiple conditions, such as replacing values only in rows where a specific column matches a criterion. For simple string replacements across entire lines, sed is generally faster and requires less code. However, when the replacement depends on the context of other fields or requires arithmetic operations, awk is the superior choice. Both tools complement each other well in shell scripts, allowing you to leverage sed for quick fixes and awk for complex transformations.

When to Choose sed vs awk

Deciding between these tools often comes down to complexity. Use sed for straightforward find-and-replace operations, especially when working with plain text files or logs. Its simplicity makes it easy to script and automate. Use awk when you need to parse columns, apply logic based on field values, or handle structured data formats. If you need to delete words starting with a specific string instead of replacing them, consider looking at our guide on How to Delete All Words Starting with a Specific String in a File. This complements substitution tasks by showing how to remove unwanted patterns entirely.

Common Pitfalls and Best Practices

A common mistake is forgetting the g flag, resulting in only the first occurrence on each line being replaced. Another issue arises when using variables in the sed command; double quotes must be used around the expression to allow variable expansion, whereas single quotes treat the content literally.
OLD="foo"
NEW="bar"
sed -i "s/$OLD/$NEW/g" file.txt
Always validate your commands on a small sample or non-critical file before running them on production data. Creating backups with -i.bak provides a safety net. Additionally, be aware that sed behavior can vary slightly between GNU sed (common on Linux) and BSD sed (common on macOS), particularly regarding the -i flag syntax. On macOS, -i '' is required for in-place editing without backup. For related tasks, such as renaming files after modification, you might find our step-by-step guide on How to Rename a File in Linux: Step-by-Step Guide useful for managing file lifecycle operations.

Frequently Asked Questions

How do I replace a string only on specific lines?

You can specify line numbers or ranges in the sed command. For example, sed -i '10,20 s/old/new/g' file.txt will only replace the string in lines 10 through 20. This is useful for targeted edits in large configuration files.

Can I use sed to replace strings recursively in multiple files?

Yes, you can combine sed with find to process multiple files. Use find . -type f -name "*.txt" -exec sed -i 's/old/new/g' {} + to replace strings in all text files in the current directory and its subdirectories.

What if my search string contains special regex characters?

sed interprets the search pattern as a regular expression. To match literal dots, asterisks, or plus signs, you must escape them with a backslash. For example, to replace "file.txt", use sed 's/file\.txt/newfile.doc/g'.

Why is my sed command not modifying the file?

Ensure you have included the -i flag for in-place editing. Without it, sed prints to stdout. Also, check for typos in the file path and verify that the user has write permissions for the file.

Is awk faster than sed for large files?

Generally, sed is faster for simple substitutions because it is optimized for stream processing. awk has more overhead due to its full programming language features. For massive files with simple find-and-replace needs, sed is the preferred choice for performance.
Tags: linux bash sed awk

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More