1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

sedでmatchした行を置換/した行の前/後に追加

Last updated at Posted at 2022-07-18

1. マッチした行の後に追加

1.1. 文字列を追加

sed '/<matchする条件>/a <追加するコンテンツ>' <対象となるファイル>

例:

target.txt
abc
sed '/^abc$/a def' target.txt
abc
def

1.2. ファイルの中身を追加

sed -i '/<matchする条件>/r <追加するコンテンツの入ったファイル>' <対象となるファイル>

r filename

例:

target.txt
abc
content_to_add.txt
def
sed '/^abc$/r content_to_add.txt' target.txt
abc
def

2. マッチした行の前に追加

2.1. 文字列を追加

sed '/<matchする条件>/i <追加するコンテンツ>' <対象となるファイル>

例:

target.txt
abc
sed '/^abc$/i def' target.txt
def
abc

2.2. ファイルの中身を追加

sed -i $'/<matchする条件>/{e cat <追加するコンテンツの入ったファイル>\n}' <対象となるファイル>

e [command]

例:

target.txt
abc
content_to_add.txt
def
sed $'/^abc$/{e cat content_to_add.txt\n}' target.txt
def
abc

3. マッチした行をファイルの中身で置換する

3.1. マッチ条件が一行の場合

sed 's/<matchする条件>/cat <追加するコンテンツの入ったファイル>/e' <対象となるファイル>

例:

target.txt
abc
content_to_add.txt
def
sed 's/abc/cat content_to_add.txt/e' target.txt
def

3.2. 複数行マッチさせる場合

target.txt
func aaa() {
   aaa

}

func bbb() {
   bbb
}
content.txt
func aaa() {
   AAA
}
gsed "/func aaa() {/,/^}/c $(sed 's/$/\\n/' content.txt | tr -d '\n' | sed 's/.\{2\}$//')" target.txt
func aaa() {
   AAA
}

func bbb() {
   bbb
}

sed 's/$/\\n/' content.txt | tr -d '\n' は複数行あるものをfunc aaa() {\n AAA\n}\nに変換する役割

参考

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?