次のコマンドは、特定のパターンの最初のオカレンスまで印刷しますが、それ以降のオカレンスは含まないことを知っています。
sed -n '1,/<pattern>/p' <file>
sed '/<pattern>/q' <file>
たとえば、次の行を含むファイルがあるとします。
this is a cow
this is a goat
this is a some fish
this is a fishie
this is a fish
this is a lion
this is a cat
次のように出力します。
$ sed '/fish/q' file
this is a cow
this is a goat
this is a some fish
$ sed -n '1,/fish/p' file
this is a cow
this is a goat
this is a some fish
最初の行から最後の項目を含む行まで出力を開始したいと思います。魚つまり、私が望む出力は次のようになります。
this is a cow
this is a goat
this is a some fish
this is a fishie
this is a fish
達成するために使用する方法は何ですかsed
?
ベストアンサー1
この試み:
$ tac infile | sed -n '/fish/,$p' |tac
通常、sedコマンドで実行すると、最初の一致パターンから入力ファイルの終わりまですべての行が取得されます。
$ sed -n '/fish/,$p' file
this is a some fish
this is a fishie
this is a fish
this is a lion
this is a cat
だから私の解決策は次のとおりです。tac
入力ファイルからコマンドを実行すると、最後に一致したパターンが最初のパターンに変わります。結果を見るtac infile
:
$ tac infile
this is a cat
this is a lion
this is a fish
this is a fishie
this is a some fish
this is a goat
this is a cow
このtac
コマンドはコマンドと同じですcat
が、tac
ファイルを逆順に印刷します。
最初のsedコマンドを実行すると、まず入力ファイルの最後までパターンに一致するすべての行が得られます。良い:
$ tac infile | sed -n '/fish/,$p'
this is a fish
this is a fishie
this is a some fish
this is a goat
this is a cow
さて。終わりました。tac
行を元の順序に復元するには、コマンドを再実行するだけです。
$ tac infile | sed -n '/fish/,$p' |tac
this is a cow
this is a goat
this is a some fish
this is a fishie
this is a fish
完璧!