gpt4 book ai didi

linux - 令人费解的 egrep 匹配换行符

转载 作者:太空狗 更新时间:2023-10-29 11:19:49 25 4
gpt4 key购买 nike

我对以下 egrep 行为感到非常困惑:

我有一个以 LF 结尾的文件。当我对 $'\n' 进行 grep 时,所有行都按预期返回。但是,当我 grep for $'\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]$

最后,如果我用强引号对 '\n' 进行 egrep 但没有 C 风格的转义,即使没有反斜杠,我也会得到“n”的匹配项。为什么?

[pjanowsk@krakow myplay2]$ egrep '\n' sample.txt 
n

最佳答案

第一个 egrep 返回每一行,因为您的 shell 将 $'\n' 视为名为 '\n' 的变量。该变量的计算结果为空字符串,因此 egrep 看到“egrep '' sample.txt”。这将返回所有行。

我不认为 grep 或 egrep 允许匹配行尾字符本身。他们使用 EOL 将文件分成匹配或不匹配的行。

您可以使用 pcregrep,它将使用“perl 兼容”的正则表达式,并且很乐意匹配多行正则表达式。

关于linux - 令人费解的 egrep 匹配换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14241423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com