ウェブサイト検索

Linux で sed コマンドをマスターする: 包括的なガイド


導入

Linux の sed (ストリーム エディター) コマンドは、テキスト操作のための強力なユーティリティです。これにより、ユーザーはファイル内のテキストの検索、置換、挿入、削除などのさまざまな操作を実行できるようになります。このチュートリアルでは、実際の例、構文の説明、高度な使用例を含む、sed コマンドをマスターするための包括的なガイドを提供します。

sedコマンドとは何ですか?

sed コマンドは、テキストを行ごとに処理するストリーム エディタです。これにより、テキスト エディタでファイルを直接開かなくても、ファイルの内容を変更できます。テキスト処理タスクを自動化するために、シェル スクリプトやシステム管理で広く使用されています。

sed の主な機能

1.パターンマッチングと置換 2.インプレースファイル編集 3.テキストのフィルタリングと操作 4.正規表現のサポート 5.複数行の操作

sed コマンドの基本構文

sed コマンドの基本構文は、コマンド オプション、編集命令を定義するスクリプト、および処理対象のファイルという 3 つの主要コンポーネントで構成されます。

この構造により、ユーザーはコマンドの動作を指定し、テキスト変換を定義し、それらを目的のファイルに適用することができます。

  1. コマンド オプション: これらはコマンドの動作を指定するために使用されます。たとえば、-i オプションは、ファイルをその場で編集する、つまりファイルを上書きするために使用されます。

  2. スクリプト: スクリプトは編集手順を定義します。一重引用符 (') または二重引用符 (") で囲むことができます。スクリプトには、セミコロン () で区切られた 1 つ以上の編集コマンドを含めることができます。 ;)。

  3. 入力ファイル: これは処理されるファイルです。単一のファイル、またはスペースで区切られたファイルのリストを指定できます。ファイルが指定されていない場合、sed は標準入力から読み取ります。

sed コマンドの基本構文は次のとおりです。

sed [options] 'script' file

この構文では、sed はコマンド、[options] はコマンド オプション、'script' には編集コマンドが含まれ、 はコマンドです。 file は処理されるファイルです。

sed [options] 'script' file

以下の例を見るとよりよく理解できるでしょう。

sed 's/hello/world/' sample.txt

これにより、sample.txt の各行で最初に出現した「hello 」が「world 」に置き換えられます。

sed で一般的に使用されるオプション

Option Description Example
-i In-place editing sed -i 's/old/new/' file.txt
-n Suppress automatic printing sed -n '/pattern/p' file.txt
-e Execute multiple commands sed -e 's/old/new/' -e '/pattern/d' file.txt
-f Read commands from a file sed -f script.sed file.txt
-r Use extended regular expressions sed -r 's/old/new/' file.txt
-E Use extended regular expressions (similar to -r) sed -E 's/old/new/' file.txt
-z Separate lines with NUL character sed -z 's/old/new/' file.txt
-l Specify the line length for the ‘l’ command sed -l 100 'l' file.txt
-b Binary mode (do not strip the CR characters) sed -b 's/old/new/' file.txt

sed の最も一般的な使用例

以下に、sed コマンドの最も実用的な使用例をいくつか示します。

まず、理解しやすく、従いやすいように、サンプル テキスト ファイル file1.txt を作成し、それに以下のテキストを書き込んでみましょう。

cat > file1.txt

次のテキストをコピーして貼り付けます。

Linux is a family of free and open-source operating systems based on the Linux kernel.
Operating systems based on Linux are known as Linux distributions or distros.
Examples include Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

検索と置換

以下のコマンドでは、s は置換操作を指定し、/ は区切り文字です。 /Linux/ は検索パターンで、Unix は置換文字列です。

注: デフォルトでは、sed コマンドは各行の最初に出現したパターンのみを置換し、行内の 2 番目または 3 番目のパターンは置換しません。

sed 's/Linux/Unix/' file1.txt

このコマンドは、各行で最初に出現した「Linux 」を「Unix 」に置き換えます。

出力:

Unix is a family of free and open-source operating systems based on the Linux kernel.
Operating systems based on Unix are known as Linux distributions or distros.
Examples include Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Unix, and many others.

各行でグローバルに置換

置換フラグ /g (グローバル置換) は、行内に出現するすべての文字列を置換する sed コマンドを指定します。

sed 's/Linux/Unix/g' file1.txt

このコマンドは、各行に出現するすべての「Linux 」を「Unix 」に置き換えます。

出力:

Unix is a family of free and open-source operating systems based on the Unix kernel.
Operating systems based on Unix are known as Unix distributions or distros.
Examples include Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Unix, and many others.

インプレース編集

`-i を指定すると、ファイルのインプレース編集が有効になります。簡単に言えば、ファイルを上書きします。

sed -i 's/Linux/Unix/' file1.txt

このコマンドは、ファイルをその場で編集し、 file1.txt 内の「Linux 」を「Unix 」に直接置き換えます。 -i を指定しない場合、挿入は出力内でのみ行われ、ファイルの内容は変更されません。変更を永続的にするには、-i オプションを使用する必要があります。

特定の行を削除する

sed '2d' file1.txt

このコマンドは、file1.txt から 2 行目を削除します。

出力:

Unix is a family of free and open-source operating systems based on the Linux kernel.
Examples include Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Unix, and many others.

特定の行を印刷する

-n はパターンスペースの自動印刷を抑制し、p は印刷コマンドです。

sed -n '1,2p' file1.txt

このコマンドは、file1.txt の 1 行目から 2 行目を出力します。

出力:

Unix is a family of free and open-source operating systems based on the Unix kernel.
Operating systems based on Unix are known as Unix distributions or distros.

パターンに一致する行を削除する

/pattern/ はパターンを含む行と一致し、d フラグは一致した行を削除します。

sed '/kernel/d' file1.txt

このコマンドは、「kernel」という単語を含むすべての行を削除します。

出力:

Operating systems based on Unix are known as Unix distributions or distros.
Examples include Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Unix, and many others.

バックアップファイルで置き換える

以下のコマンドは、「Unix 」のすべてのインスタンスを「Linux 」に置き換え、置き換える前に古いファイルの内容を含む file1.txt.bak という名前のバックアップ ファイルを作成します。 -i.bak により、インプレース編集が有効になり、バックアップ ファイルが作成されます。

sed -i.bak 's/Unix/Linux/g' file1.txt

出力:

Linux is a family of free and open-source operating systems based on the Linux kernel.
Operating systems based on Linux are known as Linux distributions or distros.
Examples include Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

また、バックアップ ファイル file1.txt.bak のファイル内容は次のとおりです。

more file1.txt.bak
Unix is a family of free and open-source operating systems based on the Unix kernel.
Operating systems based on Unix are known as Unix distributions or distros.
Examples include Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Unix, and many others.

タブをスペースに置き換える

以下のコマンドは、各タブ文字を 4 つのスペースに置き換えます。 \t フラグはタブ文字と一致し、/g フラグは行全体のグローバル置換用です。

sed 's/\t/    /g' file1.txt

出力:

   Linux is a family of free and open-source operating systems based on the Linux kernel.
Operating systems based on Linux are known as Linux distributions or distros.
Examples     include Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

空行の削除

以下のコマンドは、file1.txt からすべての空行を削除します。 /^$ は空の行に一致し、/d フラグは一致した行を削除します。

sed '/^$/d' file1.txt

vi テキスト エディタを使用して file1.txt ファイルを編集し、空の行を追加してこのコマンドをテストできます。

パターンに一致する行を印刷する

以下のコマンドは、「Ubuntu」を含む行のみを出力します。

sed -n '/Ubuntu/p' file1.txt

-n オプションは自動印刷を抑制します。 /Ubuntu/ は、パターンを含む行と一致します。 p は一致した行を出力します。

出力:

Example includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

sed の高度な使用例

このセクションは、sed コマンドの高度でより複雑な使用例で構成されています。

行の前にテキストを挿入

以下のコマンドは、「これは挿入されたテキストです。」を挿入します。 ” file1.txt の 2 行目の前に追加します。

sed -i '2i\This is inserted text.' file1.txt

-i オプションはインプレース編集用で、2i\ フラグは 2 行目の前にテキストを挿入します。

注: -i を指定しない場合、挿入は出力内でのみ行われ、ファイルの内容は変更されません。変更を永続的にするには、sed コマンドで -i オプションを使用する必要があります。

出力:

Linux is a family of free and open-source operating systems based on the Linux kernel.
This is inserted text.
Operating systems based on Linux are known as Linux distributions or distros.
Example includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

行内で n 番目に出現したパターンを置換する

/1 または /2 フラグを使用して、行内のパターンの最初と 2 番目の出現を置き換えます。以下のコマンドは、行内で 2 番目に出現する単語「Linux 」を「Unix 」に置き換えます。

sed 's/Linux/Unix/2' file1.txt

出力:

Linux is a family of free and open-source operating systems based on the Unix kernel.
This is inserted text.
Operating systems based on Linux are known as Unix distributions or distros.
Examples includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

行の後に文字列を追加

以下のコマンドは、「これは追加されたテキストです。 ” file1.txt の 3 行目の後にあります。 -i オプションにより、変更が保存され、3a\ により指定された 3 行目の後にテキストが追加されます。

sed -i '3a\This is appended text.' file1.txt

出力:

Linux is a family of free and open-source operating systems based on the Linux kernel.
This is inserted text.
Operating systems based on Linux are known as Linux distributions or distros.
This is appended text.
Example includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

行頭の文字列を置換する

^ フラグは、行の先頭にある特定のパターンと一致するために使用されます。以下のコマンドは、「Linux 」が行の先頭にある場合にのみ、「Linux 」を「Unix 」に置き換えます。

sed 's/^Linux/Unix/' file1.txt

出力:

Unix is a family of free and open-source operating systems based on the Linux kernel.
This is inserted text.
Operating systems based on Linux are known as Linux distributions or distros.
This is appended text.
Example includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

行末の文字列を置換

以下のコマンドは「distros.」を置き換えます。 」と「distributions 」は、行末に出現する場合にのみ使用します。 $ フラグは、特定のパターンを行末に一致させるために使用されます。

sed 's/distros.$/distributions/' file1.txt

出力:

Linux is a family of free and open-source operating systems based on the Linux kernel.
This is inserted text.
Operating systems based on Linux are known as Linux distributions or distributions.
This is appended text.
Example includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

大文字と小文字を区別しない置換

以下のコマンドは、大文字と小文字の区別を無視して、「linux」を「Unix」に置き換えます。 I フラグにより、大文字と小文字が区別されずに一致します。

sed 's/linux/Unix/I' file1.txt

パターン間の線を抽出する

以下のコマンドは、「inserted 」と「appended 」の間のすべての行を出力します。

sed -n '/inserted/,/appended/p' file1.txt
  1. : 2 つのパターン間の行を照合する範囲演算子。

  2. p: 一致した行を出力します。

-n オプションは、行の自動出力を抑制します。

出力:

This is inserted text.
Operating systems based on Linux are known as Linux distributions or distros.
This is appended text.

複数のファイルを処理する

次のコマンドは、 file1.txtfile2.txt の両方で「Linux 」を「Unix 」に置き換え、ファイルを上書きします。

sed -i 's/Linux/Unix/' file1.txt file2.txt

空でない行のフォーマットと番号付け

以下のコマンドは、file1.txt 内の空でない行に行番号を追加します。

sed '/./=' file1.txt | sed 'N;s/\n/ /'
  1. /./=: 空でない行と一致し、番号を付けます。

  2. N: パターンスペースに次の行を追加します。

  3. s/\n/ /: 改行文字をスペースに置き換えます。

出力:

1 Linux is a family of free and open-source operating systems based on the Linux kernel.
2 This is inserted text.
3 Operating systems based on Linux are known as Linux distributions or distros.
4 This is appended text.
5 Example includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

特定の行番号の文字列を置換する

sed コマンドを制限して、特定の行番号の文字列を置き換えることができます。以下のコマンドは、3 行目のみの文字列「distros 」を「distributions 」に置き換えます。

sed '3 s/distros/distributions/' file1.txt

出力:

Linux is a family of free and open-source operating systems based on the Linux kernel.
This is inserted text.
Operating systems based on Linux are known as Linux distributions or distributions.
This is appended text.
Example includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

行範囲の文字列を置換する

sed コマンドに行番号の範囲を指定して文字列を置換することもできます。以下のコマンドは、1 行目から 3 行目までの間で最初に出現した「Linux 」のみを「Unix 」に置き換えます。

sed '1,3 s/Linux/Unix/' file1.txt

出力:

Unix is a family of free and open-source operating systems based on the Linux kernel.
This is inserted text.
Operating systems based on Unix are known as Linux distributions or distros.
This is appended text.
Example includes Debian, Ubuntu, Fedora, CentOS, Gentoo, Arch Linux, and many others.

大きなファイルのパフォーマンスに関する考慮事項

sed を使用して大きなファイルを処理すると、特に多数の操作や非常に大規模なデータセットを扱う場合、リソースが大量に消費される可能性があります。パフォーマンスを最適化し、sed コマンドを効率的に使用するためのヒントをいくつか紹介します。

1.-n を使用して不要な出力を最小限に抑えます - -n オプションは各行の自動印刷を抑制し、必要な出力のみが表示されるようにします。これにより、大きなファイルを操作する際のオーバーヘッドが軽減されます。

例 :

sed -n '/pattern/p' largefile.txt

2.スクリプトの簡素化 - 1 つのコマンド内の操作の数を最小限に抑えます。たとえば、複数の sed コマンドを順番に適用するのではなく、それらを 1 つのスクリプトに結合して、ファイルの読み取りを減らします。

例 :

sed -e 's/foo/bar/' -e '/pattern/d' largefile.txt

3.パイプを使用したストリーム入力: - 他のコマンドまたはストリームからのデータを処理するときは、パイプを使用して中間ファイルの作成を回避し、ディスク I/O を削減します。

例 :

cat largefile.txt | sed 's/foo/bar/' > output.txt

4.大きなファイルのインプレース編集を避ける - 大きなファイルを直接変更するのではなく、出力を新しいファイルに書き込み、正確さを確認した後に元のファイルを置き換えます。

例 :

sed 's/old/new/' largefile.txt > temp.txt && mv temp.txt largefile.txt

5.代替ベンチマーク - 非常に大きなファイルの場合は、awkperl、または grep などのツールの使用を検討してください。特定のタスクではパフォーマンスが向上する場合があります。

例 :

awk '{gsub(/old/, "new"); print}' largefile.txt > output.txt

Linux での awk コマンドの使用方法の詳細については、Linux の AWK コマンドに関するチュートリアルと Linux で AWK 言語を使用してテキストを操作する方法に関するチュートリアルを参照してください。

シェルスクリプトとの統合

sed コマンドは、反復的なテキスト操作タスクを自動化するためにシェル スクリプトでよく使用されます。以下に例を示します。

#!/bin/bashReplace all occurrences of "foo" with "bar" in input.txt and save the result
sed 's/foo/bar/g' input.txt > output.txt

このスクリプトは input.txt を処理し、変更された出力を output.txt に書き込みます。

sed と他の代替手段の比較

sed は基本的なテキスト処理に効果的で軽量なツールですが、awkperl などの最新の代替ツールは追加機能を提供しており、次のような用途に適しています。特定のタスク。主な違いと、それぞれをいつ使用するかについては次のとおりです。

sed を使用する場合

  • 素早く簡単なテキストの置換または削除。
  • ファイル内の行ベースの変換。
  • スクリプトのオーバーヘッドを最小限に抑えるタスク。

awk を使用する場合

  • CSV ファイルや TSV ファイルなどの構造化データの処理。
  • テキスト処理と並行して算術計算を実行します。
  • 入力データからフォーマットされたレポートを生成します。

例 :

awk -F, '{print $1, $3}' data.csv

これにより、CSV ファイルから最初と 3 番目のフィールドが抽出され、印刷されます。

perl を使用する場合

  • 高度な正規表現を含む複雑なテキスト操作。
  • テキスト処理とロジックまたは条件を組み合わせます。
  • コンパクトでありながら強力なスクリプトを作成します。

例 :

perl -pe 's/(error)/WARNING: $1/' logfile.txt

これにより、「error」という単語を含む行に「WARNING:」プレフィックスが追加されます。

結論

sed コマンドをマスターすると、Linux でテキストを効率的に操作および処理する能力が向上します。その強力な機能とスクリプトへのシームレスな統合により、テキストベースの操作タスクにとって価値のあるツールになります。

次のステップ

sed の基本をマスターした後は、より高度なテクニックとユースケースを学ぶことができます。 sed および関連トピックに関する以下の一連のチュートリアルを使用すると、理解を深め、テキスト処理スキルを向上させることができます。

  • sed ストリーム エディタを使用して Linux でテキストを操作するための基本
  • 中級 sed: Linux 環境でのテキスト ストリームの操作

これらのチュートリアルでは、基本的な sed 操作からより複雑なテキスト操作テクニックまで、さまざまなトピックをカバーしています。これらは、コマンド ラインでのテキスト処理に習熟したい人にとって貴重なリソースです。

よくある質問

Linux の sed コマンドとは何ですか?

Linux の sed (ストリーム エディター) コマンドは、入力ストリーム (ファイルまたはパイプラインからの入力) で基本的なテキスト変換を実行するために使用される強力なテキスト処理ツールです。テキストの検索、置換、削除、挿入ができるため、テキスト操作タスクを自動化するのに非常に役立ちます。

sed をいつ使用するか?

sed は次のシナリオで使用できます。

  • テキスト置換: ファイルまたはストリーム内の単語、フレーズ、またはパターンを置換します。
  • テキストの削除: 特定の行またはパターンを削除します。
  • インプレース編集: テキスト エディタを開かずにファイルを直接変更します。
  • バッチ処理: スクリプトを使用して複数のファイルに対して同じ操作を実行します。
  • テキストの挿入/抽出: 構成ファイルやログなどの構造化ファイルに特定のテキストを挿入または抽出します。

sed を適切に使用するにはどうすればよいですか?

sed を効果的に使用するには、次の手順に従います。

sed [options] 'command' file
  • command: sed 操作 (例: 置換の場合は s、削除の場合は d)。
  • file: 処理するターゲット ファイル。

インプレース適用前のテスト: まず、ファイルを直接変更する前に、-i' オプションを指定せずにコマンドを実行して出力を確認します。

正規表現の使用: sed の正規表現サポートを利用して、複雑なパターンを照合および操作します。

複数のコマンドをチェーンする: ; または -e を使用して、複数の sed コマンドを 1 回の操作で実行します。

sed を使用してテキストを置換するにはどうすればよいですか?

テキストを置換するには、次の構文で replace s コマンドを使用します。

sed 's/old_text/new_text/' file

例:

  • 各行で最初に出現する「 foo 」を「 bar 」に置き換えます。
sed 's/foo/bar/' file.txt
  • 出現するすべての「 foo 」をグローバルに「 bar 」に置き換えます。
sed 's/foo/bar/g' file.txt
  • インプレース置換 (ファイルを直接変更します):
sed -i 's/foo/bar/g' file.txt

sed コマンドを実行するにはどうすればよいですか?

次の基本構文を使用して、ターミナルから sed コマンドを直接実行できます。

sed 'command' filename

例 :

「error 」という単語を含む行を印刷し、log.txt という名前のファイル内の「error 」を「warning 」に置き換えるには、次のようにします。

sed 's/error/warning/' log.txt

Linux の grep コマンドと sed コマンドの違いは何ですか?

Feature grep sed
Purpose Search for patterns in one or more files Edit streams of text
Output Prints lines containing the pattern Prints the edited text
Actions Search, Filter Search, Replace, Insert, Delete
Usage grep pattern file sed 'command' file
Search and Replace Yes (limited) Yes
In-place Editing No Yes
Regular Expressions Yes Yes
Multiline Operations No Yes
Text Filtering No Yes
Common Use Cases Searching logs, Finding patterns in text Editing configuration files, Replacing text in multiple files

例 :

  • grep を使用して、log.txt 内の「error 」を検索します。
grep 'error' log.txt
  • sed を使用して、log.txt 内の「error 」を「warning 」に置き換えます。
sed 's/error/warning/g' log.txt

sed を使用して空行を削除するにはどうすればよいですか?

ファイルから空の行を削除するには、次の sed コマンドを使用します。

sed '/^$/d' file.txt

説明:

  • ^$: 空の行 (文字のない行) と一致します。
  • d: 一致した行を削除します。

例 :

コマンドを実行する前のファイルは次のようになります。

line 1

line 2

line 3

コマンドを実行した後:

sed '/^$/d' file.txt

出力は次のようになります。

line 1
line 2
line 3