grepでCRLF行末を処理する方法は?

grepでCRLF行末を処理する方法は?

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 grep2.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

このページに基づいています。次のソリューションをお試しください

https://stackoverflow.com/questions/73833/how-do-you-search-for-files-含む-dos-line-endings-crlf-with-grep-on-linu

curl -sI http://unix.stackexchange.com | head -4  | grep "200 OK$(printf '\r')" 

grep -IUlr $'\r'

おすすめ記事