0

私のファイルは.txtです:

this is for testing
so test
againa and again
zzz and ssss
this is for testing
so test
againa and again

ここで、zzz と test の間で test を抽出しようとしています。

 cat a.txt | sed -n '/zzz/,/test/p'

出力:

 zzz and ssss
 this is for testing
 so test

問題は次のとおりです。

cat a.txt | sed -n '/zzz/,/jjj/p'

ファイルに存在しない単語 (jjj) を保持しようとすると、zzzファイルの末尾からデータが返されます。何も返さないことが理想的です。

4

3 に答える 3

1

sed は、期待するほどスマートではありません。awk を使用できます。最初の正規表現を見た後、行を保存します。2 番目の正規表現にヒットしたら、キャプチャしたすべての行を出力します

awk -v regex1="zzz" -v regex2="jjj" '
    $0 ~ regex1 {start=1} 
    start {lines = lines $0 ORS} 
    start && $0 ~ regex2 {printf "%s", lines; exit}
'
于 2013-10-22T20:24:08.137 に答える
0

grep -oPここでより良いオプションになります:

$ grep -oP 'zzz[\s\S]*test' a.txt 
zzz and ssss
this is for testing
so test

grep -oP 'zzz[\s\S]*jjj' a.txt
于 2013-10-22T19:55:50.227 に答える