sedでファイルの最後の行だけを置換する

カテゴリ: Linux, Mac | タグ:

sedではsed -e "s/before/after/g"のように記載すると全ての行に対して文字列の置換を行うことがあります。

ですが、時にはファイルの最終行のみ置換したいなど処理範囲を指定したい場合があります。

このような場合はsedのアドレス指定の機能を使うことで、処理の範囲を指定することができます。

元ファイル

今回は以下のファイルを元にテストを行ってみます。

$ cat count.sql

select count(*) from users UNION ALL
select count(*) from items UNION ALL
select count(*) from orders UNION ALL

最終行のみ置換する

sedの指定がs/UNION ALL/;/gだと全ての行を置換しますが、sedのアドレス指定機能を使用して$ s/UNION ALL/;/gとすることで、最後の行のみを置換できます.

ここでは、sの手前にスペースを1つ空けて、最終行を意味する$を指定しています。

$ cat count.sql | sed -e "$ s/ UNION ALL/;/g"

select count(*) from users UNION ALL
select count(*) from items UNION ALL
select count(*) from orders;

他の行指定

行範囲の指定は、$の他にも以下のように様々な指定方法があります。

1行目のみ

$ cat count.sql | sed -e "1 s/ UNION ALL/;/g"
select count(*) from users;
select count(*) from items UNION ALL
select count(*) from orders UNION ALL

1〜2行目

$ cat count.sql | sed -e "1,2 s/ UNION ALL/;/g"
select count(*) from users;
select count(*) from items;
select count(*) from orders UNION ALL

2〜3行目

```language-bash
$ cat count.sql | sed -e "2,3 s/ UNION ALL/;/g"
select count(*) from users UNION ALL
select count(*) from items;
select count(*) from orders;

manでsedの置換場所の指定ルールを確認

sedコマンドにおける、この場所指定の方法はman sedによると、address(場所)の指定機能として記載されています

$ man sed

[DESCRIPTION]

The form of a sed command is as follows:
    [address[,address]]function[arguments]

Whitespace may be inserted before the first address and the function portions of the command.

manの結果をもう少し読み進めていくとaddress指定についての詳細な説明がありました。こちらには「$」が最終行を示すことなど、より詳しい説明があります。

$ man sed
[Sed Addresses]

An address is not required, but if specified must be a number (that counts input lines cumulatively across
input files), a dollar (``$'') character that addresses the last line of input, or a context address (which
consists of a regular expression preceded and followed by a delimiter).

A command line with no addresses selects every pattern space.

A command line with one address selects all of the pattern spaces that match the address.

A command line with two addresses selects an inclusive range.  This range starts with the first pattern space
that matches the first address.  The end of the range is the next following pattern space that matches the
second address.  If the second address is a number less than or equal to the line number first selected, only
that line is selected.  In the case when the second address is a context address, sed does not re-match the
second address against the pattern space that matched the first address.  Starting at the first line follow-
ing the selected range, sed starts looking again for the first address.

Editing commands can be applied to non-selected pattern spaces by use of the exclamation character (``!'')
function.     

Amazonでおトクに買い物する方法
AmazonチャージでポイントGET


Amazonは買いもの前にAmazonギフト券をチャージしてポイントをゲットしないと損!

こちらもおススメ

2 thoughts on “sedでファイルの最後の行だけを置換する

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です