Grepは、段落内のパターンの複数の発生を省略します。

Grepは、段落内のパターンの複数の発生を省略します。

私は1つの段落で「単語の単語の単語の単語の単語」の形式のすべての表現を見つけることを試みます。

このために私は表現を使用します。grep -E -o '([^ ]+ ){4}the( [^ ]+){5}'

しかし、この例ではecho "word1 word2 word3 word4 the word5 word6 word7 word8 word9 the quoi écrire hihi haha the a b c d e" | grep -E -o '([^ ]+ ){4}the( [^ ]+){5}'

私は結果だけを得る

word1 word2 word3 word4 the word5 word6 word7 word8 word9
quoi écrire hihi haha the a b c d e

しかし私も欲しい

word6 word7 word8 word9 the quoi écrire hihi haha the

私のコードのどこに問題がありますか?

ベストアンサー1

問題は、毎回最初に一致する部分を削除しながら、grepを繰り返し実行する必要があることです。

string="word1 word2 word3 word4 the word5 word6 word7 word8 word9 the quoi écrire hihi haha the a b c d e"

copy=$string
while m=$(grep -Eo '([^ ]+ ){4}the( [^ ]+){5}' <<<"$copy"); do
    echo "$m" | head -1    # print just the first one
    copy=${copy#* the }    # remove up to and including the _first_ " the "
done
word1 word2 word3 word4 the word5 word6 word7 word8 word9
word6 word7 word8 word9 the quoi écrire hihi haha the
quoi écrire hihi haha the a b c d e

grepまたは、bashに組み込まれている正規表現サポートを使用してください。つまり、最初の一致を印刷するために出力を解析する必要はありません。

copy=$string
# the pattern is *unquoted*
while [[ $copy =~ ([^ ]+ ){4}the( [^ ]+){5} ]]; do
    echo "${BASH_REMATCH[0]}"
    copy=${copy#* the }
done

おすすめ記事