🏡 Blamechance's Digital Cottage

Search

Search IconIcon to open search

bash-sed

Last updated Sep 20, 2023 Edit Source

# Resources:

# Usecase:

sed stands for “stream editor”.

# 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:

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:

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

# 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