Replacing Special Characters in a Text File with Linux Command Line

Abstract: Use sed to replace special characters in Linux text files while preserving data integrity and handling shell escaping correctly.

Created: 2026-10-23 by

To replace special characters in a Linux text file, use the sed command with regular expressions. For example, to replace hyphens with underscores, run sed -i 's/-/_/g' file.txt. This approach handles literal symbols, quotes, and HTML entities correctly when properly escaped, ensuring data integrity without corrupting the original file structure.

Understanding the sed Command Structure

The sed (stream editor) utility is the standard tool for performing basic text transformations on an input stream. It reads lines from a file, applies editing commands, and writes the output. The core syntax follows the pattern sed [options] 'command' filename. Understanding this structure is vital because special characters often require escaping within the command string to prevent the shell or sed from misinterpreting them as control characters rather than literal text to be replaced. The most common option is -i, which edits files in place. Without this flag, sed outputs the result to the standard output (the terminal), leaving the original file unchanged. Adding -i modifies the source file directly. For safety, especially with complex replacements, it is often wise to create a backup by using -i.bak, which creates a copy of the original file before overwriting it.

Replacing Simple Literal Characters

When dealing with simple special characters like hyphens (-) or periods (.), the replacement logic is straightforward. The general substitution command is s/pattern/replacement/g, where s stands for substitute, / acts as a delimiter, and g ensures all occurrences on a line are changed, not just the first one. For instance, if you have a SQL dump file containing table names with hyphens that need to be converted to underscores for compatibility, you would execute:
sed -i 's/-/_/g' database_dump.sql
This command scans every line in database_dump.sql and replaces every instance of a hyphen with an underscore. Because the hyphen is not a reserved regex character inside a basic bracket expression or at specific positions, it does not always require escaping in simple patterns, but escaping it as \- is safer practice to avoid ambiguity. However, characters like forward slashes (/) conflict with the default delimiter used in sed. If you need to replace paths or URLs, change the delimiter to a pipe (|) or hash (#):
sed -i 's|/path/to|/new/path|g' config.txt
Using an alternative delimiter prevents syntax errors caused by the pattern containing the same character as the separator.

Handling Complex Special Characters and Quotes

Special characters such as single quotes ('), double quotes ("), backslashes (\), and ampersands (&) require careful handling due to shell expansion rules and sed specific behaviors. The shell interprets single quotes literally, meaning nothing inside them is expanded. Therefore, to include a single quote in your search pattern, you must exit the single-quoted string, add an escaped single quote, and re-enter the single-quoted string. To replace a single quote with a double quote:
sed -i 's/'"'"'/"/g' file.txt
Here, '"'"' breaks down as: end single quote, start double quote containing a single quote, end double quote, start single quote again. This effectively passes a literal single quote to sed. The ampersand (&) is particularly tricky. In the replacement string, & represents the matched text. If you want to insert a literal ampersand into the output, you must escape it with a backslash: \&. Conversely, if you are searching for a literal ampersand in the pattern, you do not need to escape it in basic regular expressions, but doing so does no harm. Backslashes also act as escape characters. To replace a backslash with a forward slash, you must escape both the search and replacement backslashes:
sed -i 's/\\\\/\//g' file.txt
Each pair of backslashes in the shell argument results in a single literal backslash passed to sed.

HTML Encoding Considerations

If the goal is to HTML encode special characters for web display, manual sed replacements can become tedious and error-prone. Characters like & must become &, less-than signs < must become <, and greater-than signs > must become >. Since these substitutions depend on order (replacing & last is crucial to avoid double-encoding), a script or dedicated tool like xmlstarlet or Python is often more robust. However, for simple cases, chaining sed commands works:
sed -i 's/&/\&/g; s//\>/g' file.html
Note that the order matters: & is replaced first, then <, then >. If you replaced & last, the & generated by the previous steps would be re-encoded, leading to incorrect output. For related text manipulation tasks, such as removing unwanted characters from filenames or converting code structures, understanding these foundational sed principles is essential. You might find it useful to explore how to remove specific characters from file names or convert conditional statement formats in scripts. See Bash Shell - Shorter Way to Remove Last Characters from the File Name and How to convert code from test format to if fi format? for further context on text processing workflows.

Verifying Changes and Troubleshooting

Before applying sed -i globally, always test the command on a small sample or preview the output without the -i flag. Redirecting output to a new file allows you to verify that the replacements occurred exactly as intended.
sed 's/-/_/g' file.txt > test_output.txt
Inspect test_output.txt to ensure no unintended changes were made. Common issues include:
  • Empty lines removed: Ensure your pattern does not accidentally match empty strings. Using anchors like ^ (start of line) or $ (end of line) can restrict scope.
  • Partial matches: If replacing "cat" with "dog", words like "category" will become "dogegory". Use word boundaries \b if supported by your sed version (GNU sed supports \b). Example: sed 's/\bcat\b/dog/g'.
  • Encoding issues: If your file contains non-ASCII characters, ensure your locale settings match the file encoding to prevent garbled output.
By mastering these techniques, you can confidently manage text files in Linux environments, ensuring that special characters are handled precisely according to your data requirements.

Frequently Asked Questions

How do I replace multiple different characters in one pass?

You can chain multiple substitution commands within a single sed invocation by separating them with semicolons. For example, sed -i 's/a/b/g; s/c/d/g' file.txt replaces all 'a's with 'b's and all 'c's with 'd's in one pass through the file, which is more efficient than running separate commands.

Why did my ampersand get duplicated in the output?

In the replacement string, & refers to the matched pattern. If you want to insert a literal ampersand, you must escape it as \&. If you wrote & in the replacement part without escaping, sed inserted the original matched text instead of the symbol you intended.

Can I use sed to replace special characters across multiple files?

Yes, you can pass multiple file arguments to sed. The command sed -i 's/old/new/g' *.txt will process all text files in the current directory. Be cautious, as this modifies all matching files simultaneously, so ensure you have backups if the operation is critical.

What is the safest way to edit files in place?

Always use sed -i.bak instead of just sed -i. This creates a backup file with the extension .bak before modifying the original. If the replacement causes data corruption or unexpected changes, you can instantly restore the original content by renaming the backup file back to the original name.

How do I handle tabs and newlines in sed?

To match a tab character, use \t in GNU sed. For newlines, basic sed processes line-by-line, so it cannot easily match across lines. You may need to use tr to translate tabs to spaces first, or use Perl-compatible regex with sed -P if available, though multi-line handling is often better suited for tools like awk or Python scripts.

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