我一直对以下egrep行为感到困惑:
我有一个以LF结尾的文件。当我用$'\n'
搜索时,所有行都按预期返回。但是当我用$'\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结尾时,使用egrep命令搜索换行符可以匹配所有行,但是搜索回车+换行符则返回空字符串。为什么呢?
[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