Ubuntu Bash で CRLF の改行コードのファイルを探してみました

WSL(Windows Subsystem for Linux) で Ubuntu を使っていると、 Windows で CRLF で編集したテキストファイルをそのまま Ubuntu に持ってきてしまうことがあります。 そういったファイルがあるか確認したかったので調べてみました。

環境

  • Ubuntu 16.04 LTS

grep コマンド

grep コマンドで CRLF を探せないかなと思って man grep してみました。

Matcher Selection

-P, –perl-regexp

Interpret the pattern as a Perl-compatible regular expression (PCRE). This is highly experimental and grep -P may warn of unimplemented features.

-P オプションは Perl と互換のある正規表現が使えるようです。 grep コマンドの正規表現はパターンがいくつかあるみたいです。

  • extended regular expression (ERE, see below)
  • basic regular expression (BRE, see below)
  • Perl-compatible regular expression (PCRE)

ERE も BRE も試してみましたがダメでした。 CR のエスケープ文字である \r や LF のエスケープ文字である \n を認識してくれませんでした。 ので、 PCRE を使うことにしました。

PCRE は実験的な機能なようです。 実装されていない機能は警告してくれるようなので、このオプションを使ってもそれ以外に不都合はなさそうかな。

Perl と互換性のある正規表現は、 \r と記述することで CR 、 \n と記述することで LF とマッチさせる意味になるようです。

General Output Control

-l, –files-with-matches

Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.

grep コマンドの標準だと見つかった行を表示してくれるのですが、 -l オプションをつけるとファイルの名前を出力してくれるようです。 ファイルの中で複数の行が見つかっても 1 回だけファイルの名前を出力してくれました。

File and Directory Selection

-I

Process a binary file as if it did not contain matching data; this is equivalent to the –binary-files=without-match option.

-I オプションをつけるとバイナリーファイルを対象外にしてくれるようです。

File and Directory Selection

-r, –recursive

Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option.

-r オプションをつけるとディレクトリーを再帰的に検索してくれるようです。

準備

次のファイルを用意しました。

  • binary
  • CRLF
  • CR
  • LF
$ ls
binary.exe  crlf.csv  cr.md  lf.txt

CR を含むファイルを探す

調べたオプションを参考に grep コマンドを実行してみます。

$ grep -PlIr '\r' .
./cr.md
./crlf.csv

正規表現のパターンは \r と記述しました。 grep コマンドがテキストファイルを扱うときに LF で区切っていることから LF 自体をマッチさせることができないからです。 結果、 CR が 含まれるもの (CRLF のファイルと CR のファイル)が検索できました。

カレントディレクトリーだけを対象にするなら、再帰的な検索のオプション (-r) を削除して、次のように記述しても同じです。 この場合の引数は、ディレクトリーじゃなくてファイルになるので、ワイルドカードの * を指定しました。

$ grep -PlI '\r' *
crlf.csv
cr.md

これらのオプションだと CRLF のファイルは探せますが、 CR のファイルも探してしまいます。

CRLF のファイルを探す

CRLF のファイルだけを探すオプションがあるか、もう少し調べてみました。

Other Options

-z, –null-data

Treat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or –null option, this option can be used with commands like sort -z to process arbitrary file names.

-z オプションをつけると改行コードで区切らずに、 0 バイトの (ASCII 制御文字の NUL) で区切ってくれるようです。 LF は区切り文字にならないので、マッチの対象になります。 ので、 CR は \r で、 LF は \n で、探すことができるようです。

-z オプションをつけて実行してみました。 正規表現のパターンは \r\n のように記述しました。

$ grep -PlIrz '\r\n' .
./binary.exe
./crlf.csv

CR だけのファイルは対象外になったみたいです。 代わりにバイナリーのファイルが対象になってしまいました。 -I オプション(バイナリーファイルを対象外にする)が無効になってしまったようです。 -z オプションは ASCII 制御文字の NUL で区切るために、 CR や LF とかの ASCII 制御文字を扱うことになり、結果、テキストファイルとしてではなく、バイナリーファイルとして扱うことになるように見えました。

-I オプションは無駄なので削除して、次のようなコマンドになりました。

$ grep -Plrz '\r\n' .
./binary.exe
./crlf.csv

CR のファイルを探す

CR だけを探す場合は次のコマンドになりました。

$ grep -Plrz '(?=.*\r)(?!.*\r\n)' .
./binary.exe
./cr.md

\r を対象にして、 \r\n を含まないもの、という正規表現のパターンを指定しました。

LF のファイルを探す

LF だけを探す場合は次のコマンドになりました。

$ grep -Plrz '(?=.*\n)(?!.*\r\n)' .
./binary.exe
./lf.txt

\n を対象にして、 \r\n を含まないもの、という正規表現のパターンを指定しました。

大きなファイル

このオプションだと、 ASCII 制御文字の NUL で区切っているので、 NUL がないようなテキストファイルの場合、 1 つファイル全体を 1 つの区切りとして扱うことになると思うのですが、巨大なファイルを検索させたらどうなるのかな。 大丈夫かな。

次ファイルを検索してみました。

  • 1 行当たり 500 文字
  • 75 万行
  • 537MB
$ time grep -Plrz '(?=.*\n)(?!.*\r\n)' .
./big.txt
./binary.exe
./lf.txt

real    0m17.719s
user    0m10.938s
sys     0m6.547s

かなり遅くなりました。

大きなファイルが検索対象に含まれないようにして時間を測ってみます。

$ time grep -Plrz '(?=.*\n)(?!.*\r\n)' --exclude=big.txt .
./binary.exe
./lf.txt

real    0m0.024s
user    0m0.000s
sys     0m0.031s

大きなファイルがあると 17.719 秒、大きなファイルがないと 0.024 秒。 あまり実用的じゃないかもしれません。

その他のオプション

それ以外にもオプションがあるようで、気になったのを引用しておきます。

File and Directory Selection

–exclude=GLOB

Skip files whose base name matches GLOB (using wildcard matching). A file-name glob can use *, ?, and […] as wildcards, and \ to quote a wildcard or backslash character literally.

--exclude=xxx のオプションをつけると指定したファイルを対象外にしてくれるようです。 xxx のところはワイルドカードで指定することができるようです。

$ grep -PlIr '\r' --exclude=*.csv .
./cr.md

.csv ファイルが対象外になりました。

File and Directory Selection

–include=GLOB

Search only files whose base name matches GLOB (using wildcard matching as described under –exclude).

--include=xxx オプションをつけると指定したファイルのみを検索してくれるようです。 --exclude=xxx と同じで、 xxx のところはワイルドカードで指定することができるようです。

$ grep -PlIr '\r' --include=*.csv .
./crlf.csv

.csv ファイルだけが対象になりました。

file コマンド

find . -not -type d -exec file "{}" ";" | grep CRLF

bash - How do you search for files containing dos line endings (CRLF) with grep on Linux? - Stack Overflow

Stack Overflow を見ていたら file コマンドを使ったパターンがありましたので、 file コマンドも調べてみました。

file — determine file type

ファイルのタイプを決定してくれる(定めてくれる、教えてくれる)コマンドのようです。 初めて知りました。

file tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic tests, and language tests. The first test that succeeds causes the file type to be printed.

ファイルシステムテスト、マジックテスト、言語テストの 3 つのテストによって決定してくれるようです。 コマンドの内部のお話なのであまり詳しく知っておかなくてもいいのかもしれません。

The type printed will usually contain one of the words text (the file contains only printing characters and a few common control characters and is probably safe to read on an ASCII terminal), executable (the file contains the result of compiling a program in a form understandable to some UNIX kernel or another), or data meaning anything else (data is usually “binary” or non-printable). Exceptions are well-known file formats (core files, tar archives) that are known to contain binary data. When adding local definitions to /etc/magic, make sure to preserve these keywords. Users depend on knowing that all the readable files in a directory have the word “text” printed. Don't do as Berkeley did and change “shell commands text” to “shell script”.

ファイルシステムテストとマジックテストについて記載されているようです。 ここもあまり詳しく知っていなくてもよいのかもしれません。

If a file does not match any of the entries in the magic file, it is examined to see if it seems to be a text file. ASCII, ISO-8859-x, non-ISO 8-bit extended-ASCII character sets (such as those used on Macintosh and IBM PC systems), UTF-8-encoded Unicode, UTF-16-encoded Unicode, and EBCDIC character sets can be distinguished by the different ranges and sequences of bytes that constitute printable text in each set. If a file passes any of these tests, its character set is reported. ASCII, ISO-8859-x, UTF-8, and extended-ASCII files are identified as “text” because they will be mostly readable on nearly any terminal; UTF-16 and EBCDIC are only “character data” because, while they contain text, it is text that will require translation before it can be read. In addition, file will attempt to determine other characteristics of text-type files. If the lines of a file are terminated by CR, CRLF, or NEL, instead of the Unix-standard LF, this will be reported. Files that contain embedded escape sequences or overstriking will also be identified.

言語テストについて記載されているようです。 文字セットとかが影響するようです。 テキストファイルと決定されると、テキストファイルのほかの特性についても調べてくれるようです。 そこに改行コードの情報もあるようです。

file コマンドを実行してみました。

$ file *
binary.exe: PE32 executable (GUI) Intel 80386, for MS Windows
crlf.csv:   ASCII text, with CRLF line terminators
cr.md:      ASCII text, with CR line terminators
lf.txt:     ASCII text

テキストファイルには “xxx text” と表示してくれるようです。 いくつか文字セットを変えたファイルを用意して確認してみたところ次の通りでした。

  • ASCII 文字だけ: “ASCII text”
  • UTF-8: “UTF-8 Unicode text”
  • Shift JIS: “Non-ISO extended-ASCII text”

CRLF のファイルだと “, with CRLF line terminators” も併せて表示してくれるようです。 CR のファイルだと “, with CR line terminators” も併せて表示してくれるようです。 LF のファイルは Unix の標準の改行コードなので “, with …” は表示されないようです。

CRLF のファイルを探す

CRLF のファイルだけ検索する場合は次のように入力すればよさそうです。

$ file * | grep CRLF
crlf.csv:   ASCII text, with CRLF line terminators

CR のファイルを探す

CR のファイルだけ検索する場合は次のように入力すればよさそうです。

$ file * | grep 'with CR line'
cr.md:      ASCII text, with CR line terminators

LF のファイルを探す

LF のファイルだけ検索する場合は次のように入力すればよさそうです。

$ file * | grep -e 'text$'
lf.txt:     ASCII text

“text” で終わる行を検索しました。

再帰的に探す

再帰的に検索する場合は、 Stack Overflow にあったように、 find と組み合わせるとできそうです。

find - search for files in a directory hierarchy

$ find . -type f | xargs file
./binary.exe: PE32 executable (GUI) Intel 80386, for MS Windows
./cr.md:      ASCII text, with CR line terminators
./crlf.csv:   ASCII text, with CRLF line terminators
./lf.txt:     ASCII text

-type c

File is of type c:

f regular file

find コマンドはオプションなしだとディレクトリーも返してくるので、 -type f のオプションをつけて通常のファイルだけを対象にしました。

xargs - build and execute command lines from standard input

xargs コマンドは標準入力からの複数の行をまとめて繰り返し実行してくれます。

CRLF のファイルだけ表示するには、またパイプでつなげて grep コマンドに渡してあげればよさそうです。

$ find . -type f | xargs file | grep CRLF
./crlf.csv:   ASCII text, with CRLF line terminators

大きなファイル

grep コマンドでも使った次ファイルを検索してみました。

  • 1 行当たり 500 文字
  • 75 万行
  • 537MB

一瞬で終わりました。 find コマンドはファイルの大きさはあまり問題にならないのかもしれません。

終わり

Bash は 1 つのコマンドでたくさんのオプションをつけて無理やり実現しようとするより、複数の簡単なコマンドを組み合わせて実現した方がよさそうでした。

file コマンドを使ったパターンだとバイナリーファイルも対象外になるし、大きなファイルが検索対象にあっても遅くならなかったので、実用的かなと思います。

参考

この記事の参照のない引用は man xxx からコピーしてきました。