sed
sed
The sed command, short for "stream editor," is a powerful utility in Unix and Linux used for text manipulation. It allows for searching, finding, and replacing text, as well as other text processing operations.
Basic Usage
The basic syntax for the sed command is:
sed [options] 'command' [file]options: Command-line options to controlsedbehavior.command: Thesedcommand to execute.file: The file(s) to process. If no file is specified,sedreads from standard input.
Examples
Replacing Text
To replace text in a file, you can use the s (substitute) command:
sed 's/old-text/new-text/' file.txtThis command replaces the first occurrence of old-text with new-text in each line of file.txt.
To replace all occurrences of old-text with new-text in each line, add the g (global) flag:
sed 's/old-text/new-text/g' file.txtEditing a File In-Place
To edit a file in place, use the -i option:
This command replaces all occurrences of old-text with new-text in file.txt and saves the changes to the same file.
Using Regular Expressions
You can use regular expressions for more complex text manipulations. For example, to remove digits from a file:
This command removes all digits from file.txt.
Deleting Lines
To delete lines that match a pattern, use the d command:
This command deletes all lines containing pattern in file.txt.
Printing Specific Lines
To print specific lines of a file, use the -n option combined with the p (print) command:
This command prints the fifth line of file.txt.
To print a range of lines:
This command prints lines 5 to 10 of file.txt.
Advanced Usage
Applying Multiple Commands
To apply multiple sed commands, use the -e option or separate commands with a semicolon:
Or:
Using Files for Commands
To use a file containing sed commands, use the -f option:
The commands.sed file might contain:
Inserting and Appending Lines
To insert text before a line, use the i command:
To append text after a line, use the a command:
Changing Lines
To replace a line that matches a pattern with new text, use the c command:
Practical Use Cases
Batch File Renaming
To rename files by replacing text in their names:
Configuration File Editing
To change settings in configuration files:
Log File Processing
To extract and process log entries:
Summary
The sed command is a versatile tool for text manipulation in Unix and Linux, capable of performing a wide range of operations from simple text substitutions to complex data transformations. Understanding and utilizing its powerful features can greatly enhance your ability to process and manipulate text files efficiently.
help
Last updated