다음을 포함하는 파일을 grep하면
These are words
These are words
These are words
These are words
… 단어 These에 대해서는 문자열을 These are words네 번 인쇄합니다 .
grep이 반복되는 문자열을 두 번 이상 인쇄하지 못하게하려면 어떻게합니까? 그렇지 않으면 grep의 출력을 조작하여 중복 행을 제거하려면 어떻게해야합니까?
답변
유닉스 철학은 한 가지 일을 잘 수행하는 도구를 갖추는 것입니다. 이 경우 grep파일에서 텍스트를 선택하는 도구입니다. 중복이 있는지 확인하기 위해 텍스트를 정렬합니다. 중복을 제거하기 위해 -u옵션을 사용합니다 sort. 그러므로:
grep These filename | sort -u
sort많은 옵션이 있습니다 : 참조 man sort. 중복 수를 계산하거나 중복 여부를 결정하기 위해 더 복잡한 체계를 원하면 정렬 출력을 uniq: 로 파이프하고 옵션에 grep These filename | sort | uniq대해서는 manuniq`을 참조하십시오 .
답변
grep단일 문자열 만 찾는 경우 및 추가 스위치 사용
grep -m1 'These' filename
에서 man grep
-m NUM, --max-count=NUM
Stop reading a file after NUM matching lines. If the input is
standard input from a regular file, and NUM matching lines are
output, grep ensures that the standard input is positioned to
just after the last matching line before exiting, regardless
of the presence of trailing context lines. This enables a calling
process to resume a search. When grep stops after NUM matching
lines, it outputs any trailing context lines. When the -c or
--count option is also used, grep does not output a count greater
than NUM. When the -v or --invert-match option is also used, grep
stops after outputting NUM non-matching lines.
또는 awk 😉 사용
awk '/These/ {print; exit}' foo