为什么grep不给出匹配线?

时间:2013-08-10 05:26:05

标签: grep

我刚刚注意到了

grep -rni 'a2}' *

不会给所有具有字符串a2} 匹配行的文档。为什么会这样?

我尝试创建一个最小的示例,但是当我创建一个新文件并粘贴内容时,它会失败。所以我已将文件上传到Git repository。也许这是一个编码问题。

该文件的内容是:

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{KV-Diagramme}
\label{chap:a2}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \PsTexAbbildungOhneCaption{figures/a2-1}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "skript"
%%% End:

grep -rni 'a2}' *的结果是

moose@pc08 ~/Downloads/algorithms/grep $ grep -rni "a2}" *
%%% End:master: "skript"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

但我期待

moose@pc08 ~/Downloads/algorithms/grep $ grep -rni "a2}" *
\label{chap:a2}

为什么我会得到这个结果?

2 个答案:

答案 0 :(得分:0)

该文件具有CR行终止符,因此它看起来像一个单行文件:

#> file anhang-2.tex
anhang-2.tex: LaTeX document, ASCII text, with CR line terminators

将其转换为Linux格式:

#>  mac2unix anhang-2.tex
mac2unix: converting file anhang-2.tex to Unix format ...
#>  grep -rni 'a2}' anhang-2.tex 
3:\label{chap:a2}

答案 1 :(得分:0)

这是因为您的文件使用的是Mac OS 9行结尾。您需要先转换为UNIX行结尾。如何执行此操作取决于您的方案,但您可以使用此文件执行一个文件:

tr '\r' '\n' < anhang-2.tex > anhang-2.txt

然后你就可以grep那个新文件了。