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.
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.
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.txtTo edit a file in place, use the -i option:
sed -i 's/old-text/new-text/g' file.txtThis command replaces all occurrences of old-text with new-text in file.txt and saves the changes to the same file.
You can use regular expressions for more complex text manipulations. For example, to remove digits from a file:
sed 's/[0-9]//g' file.txtThis command removes all digits from file.txt.
To delete lines that match a pattern, use the d command:
sed '/pattern/d' file.txtThis command deletes all lines containing pattern in file.txt.
To print specific lines of a file, use the -n option combined with the p (print) command:
sed -n '5p' file.txtThis command prints the fifth line of file.txt.
To print a range of lines:
sed -n '5,10p' file.txtThis command prints lines 5 to 10 of file.txt.
To apply multiple sed commands, use the -e option or separate commands with a semicolon:
sed -e 's/old-text/new-text/g' -e 's/another-old-text/another-new-text/g' file.txtOr:
sed 's/old-text/new-text/g; s/another-old-text/another-new-text/g' file.txtTo use a file containing sed commands, use the -f option:
sed -f commands.sed file.txtThe commands.sed file might contain:
s/old-text/new-text/g
s/another-old-text/another-new-text/g
To insert text before a line, use the i command:
sed '/pattern/i\new line of text' file.txtTo append text after a line, use the a command:
sed '/pattern/a\new line of text' file.txtTo replace a line that matches a pattern with new text, use the c command:
sed '/pattern/c\new line of text' file.txtTo rename files by replacing text in their names:
for file in *.txt; do
new_file=$(echo "$file" | sed 's/old-text/new-text/')
mv "$file" "$new_file"
doneTo change settings in configuration files:
sed -i 's/setting1=value1/setting1=value2/' config.cfgTo extract and process log entries:
sed -n '/ERROR/p' logfile.log > error.logThe 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.