![grep에서 CRLF 줄 끝을 처리하는 방법은 무엇입니까?](https://linux55.com/image/98646/grep%EC%97%90%EC%84%9C%20CRLF%20%EC%A4%84%20%EB%81%9D%EC%9D%84%20%EC%B2%98%EB%A6%AC%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95%EC%9D%80%20%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C%3F.png)
CRLF 줄 끝이 포함된 임의의 텍스트 입력이 있다고 가정해 보겠습니다.
$ curl -sI http://unix.stackexchange.com | head -4
HTTP/1.1 200 OK
Cache-Control: public, max-age=60
Content-Length: 80551
Content-Type: text/html; charset=utf-8
$ curl -sI http://unix.stackexchange.com | head -4 | hexdump -C
00000000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d |HTTP/1.1 200 OK.|
00000010 0a 43 61 63 68 65 2d 43 6f 6e 74 72 6f 6c 3a 20 |.Cache-Control: |
00000020 70 75 62 6c 69 63 2c 20 6d 61 78 2d 61 67 65 3d |public, max-age=|
00000030 36 30 0d 0a 43 6f 6e 74 65 6e 74 2d 4c 65 6e 67 |60..Content-Leng|
00000040 74 68 3a 20 38 30 39 30 32 0d 0a 43 6f 6e 74 65 |th: 80902..Conte|
00000050 6e 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 68 74 |nt-Type: text/ht|
00000060 6d 6c 3b 20 63 68 61 72 73 65 74 3d 75 74 66 2d |ml; charset=utf-|
00000070 38 0d 0a |8..|
00000073
GNU grep
2.26은 줄 끝의 측면에서 이러한 유형의 입력을 잘 처리하지 않습니다.
$ curl -sI http://unix.stackexchange.com | head -4 | grep '200 OK$'
$ curl -sI http://unix.stackexchange.com | head -4 | grep '200 OK.$'
HTTP/1.1 200 OK
이것은 약간 짜증나는 일입니다. 물론 dos2unix
파이프라인에 다음을 포함시켜 이 문제를 해결할 수 있습니다.
$ curl -sI http://unix.stackexchange.com | head -4 | dos2unix | grep '200 OK$'
HTTP/1.1 200 OK
하지만 약간 투박한 느낌이 듭니다(그리고 휴대성이 좋지 않습니다).
grep(2)
일반적으로 매뉴얼 페이지에서는 입력이 바이너리로 감지되지 않는 한 도구가 입력에서 모든 CR을 제거한다고 주장하는 것이 이상합니다 .
-U, --binary
Treat the file(s) as binary. By default, under MS-DOS and MS-Windows,
grep guesses whether a file is text or binary as described for the
--binary-files option. If grep decides the file is a text file, it
strips the CR characters from the original file contents (to make
regular expressions with ^ and $ work correctly). Specifying -U
overrules this guesswork, causing all files to be read and passed to
the matching mechanism verbatim; if the file is a text file with CR/LF
pairs at the end of each line, this will cause some regular
expressions to fail. This option has no effect on platforms other
than MS-DOS and MS-Windows.
편집하다:맨페이지에 설명된 대로 이 동작은 MS-DOS 및 MS-Windows에만 해당됩니다.
grep
입력을 전처리하지 않고 CRLF(및 CR) 줄 끝을 투명하게 처리 할 수 있습니까 ? 그렇지 않다면 패치해야 합니까, 아니면 합당한 이유가 있습니까?
답변1
이 페이지를 기반으로 합니다. 다음 솔루션을 사용해 보세요
curl -sI http://unix.stackexchange.com | head -4 | grep "200 OK$(printf '\r')"
grep -IUlr $'\r'