![grep을 사용하여 마커 주변의 n 단어에 대한 구두점 문제를 확인하세요.](https://linux55.com/image/119078/grep%EC%9D%84%20%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC%20%EB%A7%88%EC%BB%A4%20%EC%A3%BC%EB%B3%80%EC%9D%98%20n%20%EB%8B%A8%EC%96%B4%EC%97%90%20%EB%8C%80%ED%95%9C%20%EA%B5%AC%EB%91%90%EC%A0%90%20%EB%AC%B8%EC%A0%9C%EB%A5%BC%20%ED%99%95%EC%9D%B8%ED%95%98%EC%84%B8%EC%9A%94..png)
파일을 처리하려고 합니다. 내 시도는 실패했습니다. 입력 파일은 원하는 출력을 설명합니다.
입력 파일:
이는 토큰이지만 구두점이 발견되면 추출이 중지됩니다.
특정 태그 주위에 n 단어를 가져오고 싶습니다. 즉, 태그 앞의 n 단어와 태그 뒤의 n 단어입니다. 다른 솔루션에서 제공되는 것처럼 복구 모드가 없습니다.
도와주세요. 감사해요.
사용된 명령:
$ grep -io -E '(\w+ ){0,5}\b(token)\b( \w+){0,5}' grepping-n-words-around-token
산출:
This is a token
n words around a specific token
meaning n words before the token and n words after the
token
원하는 출력:
This is a token, but when any punctuation is
n words around a specific token, meaning n words before the
meaning n words before the token and n words after the
and n words after the token. There is no fix pattern
답변1
grep -o
GNU가 동일한 텍스트(예: meaning n words before the
또는 )를 두 번 출력 하도록 할 수는 없습니다 and n words after the
. 그러나 where is thpcregrep
캡처링 그룹을 사용 하고 forehead 연산자에서 일치하는 항목을 캡처하여 이를 수행할 수 있습니다(이렇게 하면 커서가 다음 일치 항목으로 이동하지 않습니다).-o<n>
n
n
$ pcregrep -o0 -o2 '(\w+\W+){0,5}token(?=((\W+\w+){0,5}))' file
This is a token, but when any punctuation is
n words around a specific token, meaning n words before the
meaning n words before the token and n words after the
and n words after the token. There is no fix pattern
-o0
전체 텍스트가 일치하는지 여부는 -o1
예측 연산자 내에서 일치하는 것입니다.(....)
(?=(here))
다음과 같은 입력에 유의하세요.
6 5 4 3 2 1 token token 1 2 3 4 5 6
그것은 다음을 제공합니다:
5 4 3 2 1 token token 1 2 3 4
token 1 2 3 4 5
첫 번째 일치 이후 두 번째 일치를 찾기 시작하기 때문입니다.토큰이므로 0
두 번째 단어 앞의 단어 만 검색됩니다 token
.
$ echo 6 5 4 3 2 1 token token 1 2 3 4 5 6 |
pcregrep -o1 '(?=((\w+\W+){0,5}token(\W+\w+){0,5}))\w*'
5 4 3 2 1 token token 1 2 3 4
4 3 2 1 token token 1 2 3 4 5
3 2 1 token token 1 2 3 4 5
2 1 token token 1 2 3 4 5
1 token token 1 2 3 4 5
token token 1 2 3 4 5
token 1 2 3 4 5
아마도 당신이 원하는 것이 아닐 수도 있습니다(각 "토큰" 앞에 최대 5개의 단어가 있더라도).
"토큰"이 나올 때마다 양쪽에 최대 5개의 단어로 라인을 생성하려면 혼자서는 쉽지 않은 것 같아요 pcregrep
.
각 "태그된" 단어의 위치를 기록한 다음 up-to-5-words<that-position>"token"up-to-5-words
각 위치를 일치시켜야 합니다.
그것은 다음과 같습니다:
$ echo 6 5 4 3 2 1 token token 1 2 3 4 5 6 | perl -lne '
my @positions; push @positions, $-[0] while /\btoken\b/g;
for $o (@positions) {
print $& if /(\w+\W+){0,5}(?<=^.{$o})token(\W+\w+){0,5}/
}'
5 4 3 2 1 token token 1 2 3 4
4 3 2 1 token token 1 2 3 4 5
아니면 어느 쪽인지 명확히 하세요.토큰모든 경우에 일치:
$ echo 6 5 4 3 2 1 token token 1 2 3 4 5 6 | perl -lne '
my @positions; push @positions, $-[0] while /\btoken\b/g;
for $o (@positions) {
print "$1<token>$3" if /((\w+\W+){0,5})(?<=^.{$o})token((\W+\w+){0,5})/
}'
5 4 3 2 1 <token> token 1 2 3 4
4 3 2 1 token <token> 1 2 3 4 5
(단순화/최적화할 수 있기를 바랍니다).