
sed
一致した行とその間の行を含めずに、一致した行の後の 2 行目 (または任意の数) を削除するには、どのようにすればよいですか?
例えば:
Enter command below
> login
Command valid
Enter your password at the below prompt
Remember to make sure no-one is looking at your screen
> mysecretword
Password accepted
「以下のプロンプトでパスワードを入力してください」の行の 2 行後にあるため、「> mysecretword」の行のみを削除したいのですが、ファイルの先頭から何行目かに一致が現れる可能性があるため、絶対行番号位置は使用できません。
オンラインで検索すると、 のような解決策がたくさん見つかりますsed '/Enter your password.*/,+3d' filex
が、これにより、「パスワードを入力してください...」行とそれに続く行も削除されてしまうため、これは私が望んでいることではありません。一致後の特定の行数の 1 行のみを削除したいのです。
sed
これを(または他の一般的に利用可能なツールで)実行するにはどうすればよいですか?
答え1
多分
sed '/^Enter your password/ {
n
n
d
}' file
または同等:
$ sed '/^Enter your password/ {n;n;d;}' file
Enter command below
> login
Command valid
Enter your password at the below prompt
Remember to make sure no-one is looking at your screen
Password accepted
答え2
一般的なケースについては、Ed Morton によるこの優れた回答を参照してください。一致するパターンに続く行を sed または awk で印刷する 。
d) 正規表現の後の N 番目のレコードを除くすべてのレコードを出力します。
awk 'c&&!--c{next}/regexp/{c=N}1' file
与えられた入力を申請する
$ awk 'c && !--c{next} /^Enter your password/{c=2} 1' ip.txt
Enter command below
> login
Command valid
Enter your password at the below prompt
Remember to make sure no-one is looking at your screen
Password accepted
/^Enter your password/{c=2} 1
一致c
後のn行目は無視され、1
入力レコードが印刷されますc && !--c{next}
isは短絡演算子なので、 falseと評価される&&
限り減算されません。値が設定された後は、その値に達しない限り減算されます。c
c
c
0
答え3
sed '/Enter your password.*/{N;p;N;d;}' file