copied!
string sed

[sed] Run and understand. A list of sed command usage instructions

created-2026/03/24 updated-2026/03/25

Introduction

This article introduces articles using the sed command.
By executing the commands listed in each article one line at a time, you can verify their behavior on Ubuntu, macOS, and Windows, so please take a look if you’re interested.

What is the sed command?

The sed command is used to perform operations on input strings.
Strings are read from files or standard input.

Feature List

This article explains the following features:

  1. Delete
  2. Replace
  3. Extract
  4. Add
  5. Write

How do I delete a string using the sed command?

The second line of the input string can be deleted by writing it in the following format.

echo -e "aaa\nbbb\nccc" | sed '2d'

If you’d like to quickly check the functionality using a file, please refer to the article below.

  1. Delete specific lines in a file
  2. Delete rows within the specified range.
  3. Delete the last line in the file.

How do I replace a string using the sed command?

The following format will replace the first occurrence of “aaa” in the input string with “bbb”.

echo "aaabbbccc" | sed 's/aaa/bbb/'

If you’d like to quickly check the functionality using a file, please refer to the article below.

  1. Replace trailing newlines.
  2. Replace the nth arbitrary string in each line.
  3. Replace a given string with a specified character.

How do I extract a string using the sed command?

The second line of the input string can be extracted by writing it in the following format.

echo -e "aaa\nbbb" | sed -n '2p'

If you’d like to quickly check the functionality using a file, please refer to the article below.

  1. Display a specific line in the file
  2. Display rows within the specified range.
  3. Display the last line in the file.

How do I add a string using the sed command?

The second line will be added as ddd by writing it in the following format.

echo -e "aaa\nbbb\nccc" | sed '2i\
ddd'

If you’d like to quickly check the functionality using a file, please refer to the article below.

  1. Add a string to the beginning of the specified line.
  2. Add a string to the line following the specified line.

How do I write to a file using the sed command?

The following format will write ddd to the second line of test1.txt.

Ubuntu、Windows

sed -i '2i\
ddd' test1.txt

macOS

sed -i '' '2i\
ddd' test1.txt

If you’d like to quickly check the functionality using a file, please refer to the article below.

  1. Add a string to a specified line number in a file
  2. Add a newline to a target file using the sed command
  3. Create backup and add to file
©︎ 2025-2026 todo