Grep은 단락에서 패턴의 여러 발생을 생략합니다.

Grep은 단락에서 패턴의 여러 발생을 생략합니다.

나는 한 단락에서 "단어 단어 단어 단어 단어 단어" 형식의 모든 표현을 찾으려고 노력합니다.

이를 위해 나는 표현을 사용합니다.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

관련 정보