0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

grep コマンドのバイナリ・マッチ・メッセージ(テキストとして不正なバイトデータが含まれている)

Last updated at Posted at 2021-03-07

こんにちは。
grep コマンドへ、不正なバイナリーバイトが含まれているテキストデータを渡した場合を調べました。

マッチ自体は成立したが不正なバイトデータを検出した場合には、デフォルトでは標準エラー出力へメッセージを出力し(binary file matches)、通常のマッチ結果は出力せず処理終了するようです1 2(終了ステータスはマッチ成立を意味する 0)。

このような場合に、-a (--text) オプションを指定すると最後まで通常処理を続けます(下記例)。ただし、出力には不正なバイナリーバイトが含まれている可能性があります。

また巨大なデータの末尾に不正なバイトデータが含まれているような場合は、処理冒頭では未検出のためか、検出までは通常処理を続けるようです。メッセージを見ると気がつくことになります。

$ printf 'oooooooooooooooooooo\nA\0' | ggrep -a 'A'
A
$ printf 'oooooooooooooooooooo\nA\0' | tr -d '\0' | ggrep 'A'
A
$ printf 'oooooooooooooooooooo\nA\0' | strings | ggrep 'A'
$ printf 'oooooooooooooooooooo\nA\0' | ggrep 'A'
ggrep: (standard input): binary file matches
$ ggrep -V | head -n1
ggrep (GNU grep) 3.6

テキストデータに不正なバイトが含まれているかどうかを判定する方法

テキストデータに不正なバイトが含まれていることを検出する方法を調べました。しかし、どれも必ずしも率直に信じると危ないようです。

  1. grep コマンド利用。マッチ成立条件で動かし、メッセージ binary file matches の有無を調べる。
  2. nkf --guess コマンド利用。BINARY と判定。
  3. file コマンド利用。data と判定。ただし UTF-8 Unicode text, with very long lines と判定される事例もある。
  1. 参考:「grep の「バイナリファイル (標準入力) に一致しました」が出る条件を調べていたらそれは長い旅路の始まりだった。

  2. GNU grep 3.4 以前では、標準エラー出力ではなく、標準出力へメッセージが出力されます( Binary file (standard input) matches)。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?