Linux 具有特定字符计数的Grep行,包括换行符

Linux 具有特定字符计数的Grep行,包括换行符,linux,bash,shell,unix,sh,Linux,Bash,Shell,Unix,Sh,我需要grep只有一定长度的行,但也包括换行符/换行符。因此,第一行将比另一行长一个字符 例如: 我使用grep如下: grep -E "^.{length}$" 结果是打印两行,因为它们的字符数相同,因为它不将\n行计数为字符 谢谢你的建议 假设您已将内容保存到名为file.txt的文件中,则可以尝试以下操作: cat file.txt | awk 'length($0) > 38 它将只输出长度大于38个字符的行: "Random text with certain length\

我需要grep只有一定长度的行,但也包括换行符/换行符。因此,第一行将比另一行长一个字符

例如:

我使用grep如下:

grep -E "^.{length}$"
结果是打印两行,因为它们的字符数相同,因为它不将\n行计数为字符


谢谢你的建议

假设您已将内容保存到名为file.txt的文件中,则可以尝试以下操作:

cat file.txt | awk 'length($0) > 38
它将只输出长度大于38个字符的行:

"Random text with certain length\n" <br>
然后显示两行,因为它们都有37个字符

不确定这是否是你一开始想要的。。。无论如何,试试看

TL;博士

对我来说,获得建议结果的最简单方法是在将管道连接到grep(即fold)之前,用sed替换换行符。然后,如有必要,展开

$ echo -e '"Random text with certain length\n"\n"Random text with certain length"\n' | sed -e ':a;N;$!ba;s/\n"/+"/g' -e '/"+/s//"\n/g' | grep -E "^.{33}$"
"Random text with certain length"
$ echo -e '"Random text with certain length\n"\n"Random text with certain length"\n' | sed -e ':a;N;$!ba;s/\n"/+"/g' -e '/"+/s//"\n/g' | grep -E "^.{34}$"
"Random text with certain length+"
$ echo -e '"Random text with certain length\n"\n"Random text with certain length"\n' | sed -e ':a;N;$!ba;s/\n"/+"/g' -e '/"+/s//"\n/g' | grep -E "^.{34}$" | sed -e '/+"/s//\n"/g'
"Random text with certain length
"
谢谢你澄清描述。以下部分内容参考了前面的描述,但删除似乎是浪费

我不确定我是否完全理解并做出了一些假设

这些行都有双引号,或者至少是折叠/展开要计数的新行所特有的。 CR+LF或LF单独被视为“换行/换行” 在描述中,\n LF/$可能意味着\r CR/^M。它与wc的引用一起工作。否则,GRIP和WC都不会考虑线路长度相同。 换句话说,如上所述,默认情况下,grep不将换行符\n计算为字符,但将回车计数为字符,而wc将两者都计算为字符

这确认了\n=换行符$和\r=回车^M

\n=换行符

\r=回车

对于grep,回车是一个额外字符。换行符不是

这将为两行生成相同的字符计数和结果

echo -en '\n' | sed -e '/\r/s///g' | grep -E "^.{1}" | wc -c
0
echo -en '\r' | sed -e '/\r/s///g' | grep -E "^.{1}" | wc -c
0
给定按行长度过滤的条件,grep-E本身永远不会将换行/LF作为字符计算,因此不能这样做。另一个例子是,两条线在视觉上是相同的长度,但实际上不是相同的长度

$ echo -e 'hello\r\nworld\n'
hello
world
$ cat <<< "$(echo -e 'hello\r\nworld\n' | grep -E "^.{5}$")"
world
$ cat <<< "$(echo -e 'hello\r\nworld\n' | grep -E "^.{6}$")"
hello

我不确定它是否有效,但请尝试grep-E^.{`wc-c`}$.^。{length}$| ^.{length-1}$\n也可能是您要查找的内容,等等。这将与grep执行相同的操作,它不将换行符计算为字符。因此,如果grep不以这种方式工作,我应该使用什么来产生一个'\n'差异?我基本上只需要获取字符数,包括\n我理解得稍微好一点的\n现在,似乎您需要替换一些\n而不是全部。我添加了一个TL;DR基于您的输出。也许这就是你想要做的?这可能也有帮助。
$ echo -en '\n' | wc -c
1
$ echo -en '\n' | grep -E "^.{1}" | wc -c
0
$ echo -en '\r' | wc -c
1
$ echo -en '\r' | grep -E "^.{1}" | wc -c
2
echo -en '\n' | sed -e '/\r/s///g' | grep -E "^.{1}" | wc -c
0
echo -en '\r' | sed -e '/\r/s///g' | grep -E "^.{1}" | wc -c
0
$ echo -e 'hello\r\nworld\n'
hello
world
$ cat <<< "$(echo -e 'hello\r\nworld\n' | grep -E "^.{5}$")"
world
$ cat <<< "$(echo -e 'hello\r\nworld\n' | grep -E "^.{6}$")"
hello
$ cat <<< "$(echo -e 'hello\r\nworld\n' | sed -e '/\r/s///g' | grep -E "^.{5}$")"
hello
world
$ cat <<< "$(echo -e 'hello\r\nworld\n' | sed -e '/\r/s///g' | grep -E "^.{6}$")"
<no output>