Skip to content

Basic usage of sed command

sed, also known as stream editor, is a commonly used text processing tool in Linux.

homepage-banner

Introduction

Sed, which stands for stream editor, is a powerful command-line tool used in Linux and Unix systems to perform text manipulation tasks. It is used to filter, search and replace text in files or streams. Sed is a versatile text editor that can be used for a wide range of text manipulation tasks.

Basic Syntax

The basic syntax of sed is straightforward. The syntax is as follows:

sed [options] 'command' file
sed line_range pattern/RegExp/ file

Here, the command is the action that sed takes on each line of the file, and the file is the name of the file to be processed. The options are used to modify the behavior of sed.

d          Delete
p          Print the lines that match a pattern
a \string  Append a line
i \string  Insert a line
r          Append text after a line
w          Write to another file
s/pattern/string/    Search and replace (only the first match on each line)
s/pattern/string/g   Global search and replace

(1) Replace the third line of test.txt with “hello” and output:

#!/bin/bash
sed "3c hello" test.txt

(2) Replace the third line of test.txt with “hello” and save to the original file:

#!/bin/bash
sed -i "3c hello" test.txt

(3) Delete the first three lines of test.txt:

sed '1,3d' test.txt

(4) Delete the fourth line to the last line of test.txt:

sed '4, $d' test.txt

(5) Delete the lines that contain “hello”:

sed '/hello/d' test.txt

(6) Delete two lines after the fifth line:

sed '5, +2d' test.txt

(7) Append a line “world” after the line that starts with “hello”:

sed '/^hello/a world' test.txt

(8) Write the lines that contain “abc” to a file named b.txt:

sed '/abc/w b.txt' test.txt

(9) Replace the lines that start with “#” in /etc/fstab with “#*#”:

sed 's/^#/#*#/' /etc/fstab

(10) Use sed to remove color codes from the output that has colors:

sed "s,\x1B\[[0-9;]*[a-zA-Z],,g"

Conclusion

Sed is a powerful tool that can be used to perform various text manipulation tasks. It is a versatile tool that can be used for both simple and complex text manipulation tasks. The commands provided by sed are easy to use and can be combined to perform complex tasks. Sed is an essential tool for anyone who works with text files in Linux or Unix systems.

Leave your message