Search
Search Icon Icon to open search bash-sed Last updated
Sep 20, 2023
Edit Source
# Resources:# Usecase:sed
stands for “stream editor”.
It can perform text search and replace, insertion and deletion. sed
is 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:1
sed [ options] command [ input-file]
With piping:
Piping allows manipulation of output from other commands, or even chains of commands.
1
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:
1
sed '/pattern/d' filename.txt
To delete the first or last line :
1
2
3
4
5
6
#Delete first line:
sed -i '1d' filename
#Delete last line:
sed '$d' filename.txt
To delete line from range x to y :
1
sed 'x,yd' filename.txt
To delete from nth to last line :
1
2
3
4
5
sed 'nth,$d' filename.txt
#e.g:
sed '12,$d' filename.txt
# Generic snippets:# To find and replace text:1
sed 's/foo/bar/g' file.txt
This command will find all instances of the word “foo” in the file file.txt
and replace them with the word “bar”. The g
flag 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:
1
sed '3 s/unix/linux/' geekfile.txt
# Replacing 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.
1
sed 's/unix/linux/3g' geekfile.txt
# Printing 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.
1
sed -n 's/unix/linux/p' geekfile.txt
# Replacing strings only from a range of lines :You can specify a range of line numbers to the sed command for replacing a string.
1
sed '1,3 s/unix/linux/' geekfile.txt