sed + 最初の一致または2番目の一致から文字を削除する

sed + 最初の一致または2番目の一致から文字を削除する

次のsed構文は、「すべて付与が必要」行から「#」を削除します。

   sed 's/#\([[:space:]]*Require all granted\)/ \1/' graphite-web.conf

   #<IfModule mod_authz_core.c>
   #    # Apache 2.4
   #    Require local
   #    Order Allow,Deny
   #    Allow from All
        Require all granted
   #</IfModule>
   #<IfModule !mod_authz_core.c>
   #    # Apache 2.2
        Require all granted
   #    Order Allow,Deny
   #    Deny from all
   #    Allow from All
   #    Allow from ::1
   #</IfModule>

最初の一致から "#"を削除するようにsed構文を変更するにはどうすればよいですか?それとも2番目のゲーム?

予想出力:

   #<IfModule mod_authz_core.c>
   #    # Apache 2.4
   #    Require local
   #    Order Allow,Deny
   #    Allow from All
        Require all granted
   #</IfModule>
   #<IfModule !mod_authz_core.c>
   #    # Apache 2.2
   #    Require all granted
   #    Order Allow,Deny
   #    Deny from all
   #    Allow from All
   #    Allow from ::1
   #</IfModule>

または

   #<IfModule mod_authz_core.c>
   #    # Apache 2.4
   #    Require local
   #    Order Allow,Deny
   #    Allow from All
   #    Require all granted
   #</IfModule>
   #<IfModule !mod_authz_core.c>
   #    # Apache 2.2
        Require all granted
   #    Order Allow,Deny
   #    Deny from all
   #    Allow from All
   #    Allow from ::1
   #</IfModule>

ベストアンサー1

awk代わりに使用

$ cat ip.txt 
   #    Allow from All
   #    Require all granted
   #    # Apache 2.2
   #    Require all granted
   #    Order Allow,Deny
   #    Require all granted
   #    Order Deny

$ awk '/#[[:space:]]*Require all granted/ && ++c==1{sub("#", " ")} 1' ip.txt
   #    Allow from All
        Require all granted
   #    # Apache 2.2
   #    Require all granted
   #    Order Allow,Deny
   #    Require all granted
   #    Order Deny

$ awk '/#[[:space:]]*Require all granted/ && ++c==2{sub("#", " ")} 1' ip.txt
   #    Allow from All
   #    Require all granted
   #    # Apache 2.2
        Require all granted
   #    Order Allow,Deny
   #    Require all granted
   #    Order Deny

$ awk '/#[[:space:]]*Require all granted/ && ++c>1{sub("#", " ")} 1' ip.txt
   #    Allow from All
   #    Require all granted
   #    # Apache 2.2
        Require all granted
   #    Order Allow,Deny
        Require all granted
   #    Order Deny

また、見ることができますawk は変更内容を保存します。


または以下を使用してください。perl

$ # for inplace editing, use perl -i -pe
$ perl -pe 's/#/ / if /#\s*Require all granted/ && ++$c==1' ip.txt
   #    Allow from All
        Require all granted
   #    # Apache 2.2
   #    Require all granted
   #    Order Allow,Deny
   #    Require all granted
   #    Order Deny

おすすめ記事