grepまたはvimを使用して特定の場所にテキストを挿入する

grepまたはvimを使用して特定の場所にテキストを挿入する

特定の場所にテキストを挿入する必要がありますが、ファイルは1000〜2000行に大容量であり、情報は途中またはどこにでも追加されるため、行はどこでも可能です。

以下は、例の短いバージョンです。

 1 define service{
 2         service_description             version-check-aix
 3         use                             passive-service
 4         max_check_attempts              1
 5         initial_state                   o
 6         notifications_enabled           0
 7         host_name                       hosts1,host2
 8 }
 9
10 define service{
11         service_description             version-check-unix
12         use                             passive-service
13         max_check_attempts              1
14         notifications_enabled           0
15         host_name                       hosts1,host2
16 }
17 define service{
18         service_description             version-check-linux
19         use                             passive-service
20         initial_state                   o
21         notifications_enabled           0
22         host_name                       hosts1,host2 

私の例host_name<tab><something here>,host3では、この行は15行にあります。 (行番号は説明用であり、データファイルには存在しません。)

grep -in version-check-unix「host3」を挿入できますか?どのように?

ベストアンサー1

特定の基準に一致する行にアイテムを追加しようとしています。これはsed待つことで可能です。

一致基準が次のと仮定します。行には「host_name」文字列が含まれており(一部のスペースやタブの後に)、「host3」を追加したい「hosts1、host2」が含まれています。これでこれが機能します。

cat file | sed 's/\(^[\t ]\+host_name[\t ]\+hosts1,host2$\)/\1,host3/g' > newfile

file元のファイルとnewfile新しく編集されたファイルはどこにありますか?

おすすめ記事