如何在文件中grep"\n"

Pan*_*j K 8 linux grep

示例文件:abc.ksh

echo "This is a sample file." >> mno.txt
echo "\nThis line has new line char." >> mno.txt
Run Code Online (Sandbox Code Playgroud)

我想要

echo "\nThis line has new line char." >> mno.txt
Run Code Online (Sandbox Code Playgroud)

作为输出.

fed*_*qui 17

使用-F匹配固定的字符串:

$ grep -F "\n" file
echo "\nThis line has new line char." >> mno.txt
Run Code Online (Sandbox Code Playgroud)

来自man grep:

-F, - 固定字符串

将PATTERN解释为固定字符串列表,由换行符分隔,其中任何一个都要匹配.(-F由POSIX指定.)


小智 5

最简单的方法是使用正则表达式:

grep "$" filename  # this will match all lines ending with "\n" (often all lines)
grep "PATTERN$"    # this will match all lines ending with "PATTERN\n"
Run Code Online (Sandbox Code Playgroud)

在 REGEX 语言中,$表示 EOL(行尾),所以它经常会匹配"\n"(原因很常见作为行尾)。

警告:小心使用grep支持正则表达式的版本!。