-rlwの代わりに-rnwを使用すると、Grepは空の行を返します。

-rlwの代わりに-rnwを使用すると、Grepは空の行を返します。

使用この単純なPastebinテスト文字列ここで、正規表現パターンを使用して見た最後の例が、他の2行と比較して2つの空行を提供するのはなぜですか?例1と同じ結果を見たいです。 example2からexample3への唯一の変更は、-lオプションから-nオプションに切り替えたことです。

**example1**
$ grep -rnw html5uploader
    views/layouts/test.ctp:49:       src="/js/jquery.html5uploader.min.js<?=$no_cache?>">
    views/layouts/test.ctp:52:       $("#screenshot").html5uploader(

**example2**
$ grep -rlw .*html5uploader.*
    views/layouts/test.ctp

**example3**
$ grep -rnw .*html5uploader.*
    (empty line)
    (empty line)

"test.ctp"ファイルのPastebinコンテンツ:

<!-- 
        <input type="file" name="screenshot" id="screenshot" multiple />


        <script type="text/javascript" src="/js/jquery.html5uploader.min.js<?=$no_cache?>"></script>
        <script type="text/javascript">
            // File upload
            $("#screenshot").html5uploader(
            {
                name: "screenshot",
                postUrl: "/bugs/ajax_upload_files"
            });
        </script>
 -->    </body>
</html>

ベストアンサー1

問題はソースファイルのDOS / Windows行の終わりです。

以下の最初のコマンドは空行を生成するように見えますが、2番目のコマンドはそうではありません。

$ grep -r '.*html5uploader.*'


$ grep -r '.*html5uploader.*' | hexdump -C
00000000  74 65 73 74 2e 63 74 70  3a 09 09 3c 73 63 72 69  |test.ctp:..<scri|
00000010  70 74 20 74 79 70 65 3d  22 74 65 78 74 2f 6a 61  |pt type="text/ja|
00000020  76 61 73 63 72 69 70 74  22 20 73 72 63 3d 22 2f  |vascript" src="/|
00000030  6a 73 2f 6a 71 75 65 72  79 2e 68 74 6d 6c 35 75  |js/jquery.html5u|
00000040  70 6c 6f 61 64 65 72 2e  6d 69 6e 2e 6a 73 3c 3f  |ploader.min.js<?|
00000050  3d 24 6e 6f 5f 63 61 63  68 65 3f 3e 22 3e 3c 2f  |=$no_cache?>"></|
00000060  73 63 72 69 70 74 3e 0d  0a 74 65 73 74 2e 63 74  |script>..test.ct|
00000070  70 3a 09 09 09 24 28 22  23 73 63 72 65 65 6e 73  |p:...$("#screens|
00000080  68 6f 74 22 29 2e 68 74  6d 6c 35 75 70 6c 6f 61  |hot").html5uploa|
00000090  64 65 72 28 0d 0a                                 |der(..|
00000096

0a 0d上記のバイト順を守ってください。これはDOS / Windows行の終わりを示します。

以下は必須テキストを生成します。

$ tr -d '\r' <test.ctp | grep '.*html5uploader.*'
                <script type="text/javascript" src="/js/jquery.html5uploader.min.js<?=$no_cache?>"></script>
                        $("#screenshot").html5uploader(

                        $("#screenshot").html5uploader(

したがって、問題はソースファイルtest.ctpにDOS / Windows行の終わりがあり、行全体を印刷すると出力が上書きされることです。

ファイルを変更するには、tr -d '\r'次の便利なユーティリティのいずれかを使用してください。dos2unix

この問題を回避するためにどのエディタを使用できるかについては、以下を参照してください。「どのテキストエディタがWindowsとUnixスタイルの改行を正しく処理していますか?」

おすすめ記事