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:

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:

DescriptionCommand Syntax
Replace all occurrences of a pattern with a replacement strings/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 patterni/pattern/text or a/pattern/text
Append a line to the end of the filea text
Flag to have changes written to the file-i
Delete characters that match pattern, for all linessed ‘s/[pattern]//g’
To have OR/AND operations, best to use -e flag to chain operationssed -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.txt

To delete the first or last line:

#Delete first line: 
sed -i '1d' filename
 
 
#Delete last line:
sed '$d' filename.txt

To delete line from range x to y:

sed 'x,yd' filename.txt

To delete from nth to last line:

sed 'nth,$d' filename.txt
 
#e.g: 
 
sed '12,$d' filename.txt

Generic 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.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:

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.

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.

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.

sed '1,3 s/unix/linux/' geekfile.txt