The sed command, short for "stream editor," is a powerful text processing tool in Bash. It allows users to perform various operations on text files or input streams efficiently.
sed is primarily used for:
Its strength lies in its ability to process text line by line, making it ideal for large files or streams.
The general syntax for the sed command is:
sed [options] 'command' file
Where:
options modify the behavior of sed'command' specifies the operation to performfile is the input file (optional if using standard input)Replace the first occurrence of "old" with "new" in each line:
sed 's/old/new/' file.txt
Replace all occurrences of "old" with "new" in each line:
sed 's/old/new/g' file.txt
Delete lines containing a specific pattern:
sed '/pattern/d' file.txt
Edit the file directly, creating a backup with the .bak extension:
sed -i.bak 's/old/new/g' file.txt
sed supports advanced features like:
For complex text processing tasks, consider using sed in combination with other Bash pipes and commands like grep or awk.
sed commands on a small sample before applying them to large files.The sed command is a versatile tool for text manipulation in Bash. Its efficiency in processing large files and streams makes it invaluable for system administrators and developers. By mastering sed, you can significantly enhance your text processing capabilities in Bash scripting.