Understanding the sed -i Command for In-Place File Editing
Introduction to sed -i
The sed (stream editor) command is a powerful text manipulation tool in Unix-like systems. While the standard sed outputs modified content to the terminal, the -i flag enables in-place editing, allowing direct modification of file contents without redirection.
Basic Syntax
sed [-nefr] [address]command [file]
Common Options
- -n: Suppress automatic output. Only lines processed by explicit print commands are displayed.
- -e: Execute multiple editing commands in sequence.
- -f: Read editing commands from a file instead of the commmand line.
- -r: Enable extended regular expression support.
- -i: Edit files in place, modifying the original file directly.
Address Specification
The optional address restricts commands to specific lines or ranges:
[start_line[,end_line]]command
Editing Commands
- a\: Append text after the current line.
- c\: Replace lines in the specified range with new text.
- d: Delete lines matching the address.
- i\: Insert text before the current line.
- p: Print the current line (often used with
-n). - s/pattern/replacement/flags: Substitute matching pattern with replacement text.
Practical Examples
String Replacement
The most common use of sed -i involves find-and-replace operations:
sed -i 's/old_text/new_text/' filename.txt
sed -i 's/old_text/new_text/g' filename.txt
Without the g flag, only the first occurrence per line is replaced. With g, all occurrence are substituted.
Example file contents:
d
ddd
#ff
Applying the commands:
sed -i 's/d/7523/' sample.txt
# Result:
7523
7523dd
#ff
sed -i 's/d/7523/g' sample.txt
# Result:
7523
752375237523
#ff
Removing Leading Characters
To remove a specific character from the beginning of each line, use the caret anchor in regex:
sed -i 's/^@//' targetfile
This removes the @ symbol from the start of every line.
Inserting Lines Before or After Matching Patterns
Add content relative to lines containing specific text:
# Insert a new line before lines containing "pattern"
sed -i '/pattern/i\New line content' datafile
# Append a new line after lines containing "pattern"
sed -i '/pattern/a\New line content' datafile
Deleting Lines
Remove lines matching a pattern:
sed -i '/unwanted_text/d' filename
This deletes all lines containing unwanted_text from the file.
Escaping Special Characters
When dealing with special shell characters in replacements, proper escaping is essential:
sed -i "s/\\\"/\\\\\\\\/g" temp.txt
This example escapes backslashes and quotes for replacement operations involving literal special characters.
Important Considerations
- Always create a backup before using
sed -ion important files, or usesed -i.bakto automatically generate backup files with the.bakextnesion. - Test your patterns with
sedwithout the-iflag first to verify the results. - The
-iflag behavior varies slightly across differentsedimplementations (GNU vs. BSD).