LoginSignup
0
0

sedで条件指定して置換する

Last updated at Posted at 2023-06-06

需要ありそうなのにググってもやり方出てこなかったので調べてみました。
(ググり力の問題かも)

やりたいこと

% cat hoge.txt
hoge_hello_0.1.1_hogehoge
fuga_hello_1.2.1_fugafuga
moge_hello_2.2.1_mogemoge_0.1

数字の前の _ だけ : に置換したい。

% cat hoge.txt | sed 's/_[0-9]/:/g'    
hoge_hello:.1.1_hogehoge
fuga_hello:.2.1_fugafuga
moge_hello:.2.1_mogemoge:.1

普通に数字指定すると、数字も置換されて消えちゃう。

やりかた

% cat hoge.txt | sed 's/_\([0-9]\)/:\1/g'
hoge_hello:0.1.1_hogehoge
fuga_hello:1.2.1_fugafuga
moge_hello:2.2.1_mogemoge:0.1

解説

-E オプションの有無で、基本と拡張の正規表現を選ぶ事ができます。
今回は -E オプションをつけない事で基本正規表現を選びます。
https://nxmnpg.lemoda.net/ja/7/sed

基本正規表現では \(\) で囲う事でサブ式を指定できます。
そして \1 等でサブ式を指定できます。
https://nxmnpg.lemoda.net/ja/7/re_format

上記の例では _ に続く数字だけをサブ式に代入し、置換後にサブ式の数字を戻してあげました。

行の検索

特定の行だけ置換処理の対象にしたい。って場合はこんな感じでできます。

% cat hoge.txt | sed '/fuga/s/_/:/g'
hoge_hello_0.1.1_hogehoge
fuga:hello:1.2.1:fugafuga
moge_hello_2.2.1_mogemoge_0.1

fuga を含む行の _: に置換しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0