sed コマンドを使用して特定の行があるかどうかを確認し、そうでない場合は追加します。

sed コマンドを使用して特定の行があるかどうかを確認し、そうでない場合は追加します。

ファイルにさらに端末を追加したいです/etc/securetty。具体的には、まだ存在しない場合は範囲​​内にあるpts/nものを追加したいと思います。コマンドでこれを達成できますか?私の内容は次のとおりです。n0-9sed/etc/securetty

# Local X displays (allows empty passwords with pam_unix's nullok_secure)
pts/0
pts/1
pts/2
pts/3

私は同様のことを試しました:

sudo sed '+pts/3+a pts/4' /etc/securetty

これにより、次のエラーが発生します。

sed: -e expression #1, char 3: extra characters after command

ベストアンサー1

その行に出会ったら、分数/数字を書き留めます。この-pオプションはautoprint機能します。到着したら、eofハッシュを抽出し%h、フィルタを通過してgrep印刷されていない端末を確認し、mapそれを使用してフォーマットを準備します。

perl -lpe 'm|^pts/([0-9])$| and $h{$1}++;
   END{ print for map { "pts/$_" } grep { !$h{$_} } 0 .. 9; }
' /etc/securetty

hold space数字0 1 2 ... 9に初期化します。この行に会うたびにpts/[0-9]予約されたスペースから切り取られます。でeof予約されたスペースを取得し、数字が見つかったら、正しい形式に変更して印刷する必要があります。

sed -e '
   # initialize the hold space with 0 1 ... 9
   1{x;s|.*|'"$(echo {0..9})"'|;x}

   # whatever be the line, it needs to be printed
   p

   # we meet a valid pts/ line
   \|^pts/[0-9]$|{
      # the hold space gets appended to the pattern space
      G
      # grab what is the pts number and search for it in the hold and
      # delete itand store back the changes into hold space.
      s|^pts/\([0-9]\)\n\(.*\)\1 |\2|;h
   }

   # weve not arrived at the eof and weve processed the input so go no further
   $!d

   # we are at the eof, so we bring back the hold space. just in case all
   # numbers were dealt with up, we simply bail out. Else, prepend the str 
   # pts/ to the numbers present and simply were home
   g;/[0-9]/!d;s/ //g
   s|[0-9]|pts/&\n|g;s/.$//

   # *TIP*: Sprinkle the l, list pattern space at various places to see 
   # whats going on.

' /etc/securetty 

おすすめ記事