Resources:
Usecase:
sed stands for “stream editor”.
- It can perform text search and replace, insertion and deletion.
sedis efficient in that it can make changes to the file without creating a temp file to redirect output to.- Similar in function to bash-awk, but it is not as robust and lacks logic to it’s operations.
- Though, the syntax is often easier and in one line.
Syntax:
Basic syntax:
sed [options] command [input-file]With piping: Piping allows manipulation of output from other commands, or even chains of commands.
cat report.txt | sed 's/Nick/John/g'Quick Cheatsheet:
| Description | Command Syntax |
|---|---|
| Replace all occurrences of a pattern with a replacement string | s/pattern/replacement/g |
| Delete all lines that match a pattern | /pattern/d |
| Print only the lines that match a pattern | /pattern/p |
| Insert a line before or after the line that matches a pattern | i/pattern/text or a/pattern/text |
| Append a line to the end of the file | a text |
| Flag to have changes written to the file | -i |
| Delete characters that match pattern, for all lines | sed ‘s/[pattern]//g’ |
To have OR/AND operations, best to use -e flag to chain operations | sed -e ’…’ -e ’…’ file |
Deleting lines:
This deletes lines from a file, without even needing to open it.
Delete with pattern matching:
sed '/pattern/d' filename.txtTo delete the first or last line:
#Delete first line:
sed -i '1d' filename
#Delete last line:
sed '$d' filename.txtTo delete line from range x to y:
sed 'x,yd' filename.txtTo delete from nth to last line:
sed 'nth,$d' filename.txt
#e.g:
sed '12,$d' filename.txtGeneric snippets:
To find and replace text:
sed 's/foo/bar/g' file.txt- This command will find all instances of the word “foo” in the file
file.txtand replace them with the word “bar”. - The
gflag tells sed to replace all instances of the pattern, not just the first one.
Replacing string on a specific line number:
You can restrict the sed command to replace the string on a specific line number. An example is:
sed '3 s/unix/linux/' geekfile.txtReplacing from nth occurrence, to all subsequent occurrences in a line:
Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth… “unix” word with “linux” word in a line.
sed 's/unix/linux/3g' geekfile.txtPrinting only the replaced lines:
Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.
sed -n 's/unix/linux/p' geekfile.txtReplacing strings only from a range of lines :
You can specify a range of line numbers to the sed command for replacing a string.
sed '1,3 s/unix/linux/' geekfile.txt