【发布时间】:2013-01-09 16:10:07
【问题描述】:
我一直对以下 egrep 行为感到非常困惑:
我有一个以 LF 结尾的文件。当我 grep $'\n' 时,所有行都按预期返回。但是当我 grep $'\r\n' 时,所有行都会返回,即使文件中没有回车符。为什么 grep 会出现这种令人费解的行为?
[pjanowsk@krakow myplay2]$ cat sample.txt
a
b
n
c
[pjanowsk@krakow myplay2]$ file sample.txt
sample.txt: ASCII text
[pjanowsk@krakow myplay2]$ egrep $'\n' sample.txt
a
b
n
c
[pjanowsk@krakow myplay2]$ egrep $'\r\n' sample.txt
a
b
n
c
此外,当我将文件转换为 CRLF 终止时,egreping 换行符匹配所有行,但 egreping 回车符+换行符返回空字符串。为什么?
[pjanowsk@krakow myplay2]$ unix2dos sample.txt
unix2dos: converting file sample.txt to DOS format ...
[pjanowsk@krakow myplay2]$ file sample.txt
sample.txt: ASCII text, with CRLF line terminators
[pjanowsk@krakow myplay2]$ egrep $'\n' sample.txt
a
b
n
c
[pjanowsk@krakow myplay2]$ egrep $'\r\n' sample.txt
[pjanowsk@krakow myplay2]$
最后,如果我使用强引号但没有 C 样式转义的 egrep '\n',即使没有反斜杠,我也会得到“n”的匹配项。为什么?
[pjanowsk@krakow myplay2]$ egrep '\n' sample.txt
n
【问题讨论】: