如何找到连续的空白行并将其转换为一条 [英] how to find continuous blank lines and convert them to one

查看:72
本文介绍了如何找到连续的空白行并将其转换为一条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件-a,并且存在一些连续的空行(不止一个),请参见下文:

cat a
1

2


3



4

5

所以首先我想知道是否存在继续空白行,我尝试过

cat a | grep '\n\n\n'

没有任何输出.所以我必须使用下面的方式

vi a 
:set list
/\n\n\n

所以我想知道是否存在其他shell命令可以轻松实现这一点? 那么如果存在两个和更多的空白行,我想将它们转换为一个?见下文

1

2

3

4

5

起初我尝试在shell之下

sed 's/\n\n\(\n\)*/\n\n/g' a

它不起作用,然后我尝试了这个shell

cat a | tr '\n' '$' | sed 's/$$\(\$\)*/$$/g' | tr '$' '\n'

这一次有效.而且我还想知道是否存在其他方式可以实现这一目标?

解决方案

如果您的cat实现支持

   -s, --squeeze-blank
          suppress repeated empty output lines

那么就这么简单

$ cat -s a
1

2

3

4

5

此外,-s-n都可以通过less命令使用.

备注:仅包含空格的行将不会被取消.

如果您的cat不支持-s,则可以使用:

awk 'NF||p; {p=NF}'

或者如果您想保证每条记录之后都包含空白行,包括输出末尾,即使输入中不存在空白行,那么:

awk -v RS= -v ORS='\n\n' '1'

如果您的输入包含所有空白行,并且希望将它们像非空白行一样对待(如cat -s一样,请参见下面的注释),然后:

awk '/./||p; {p=/./}'

并确保输出末尾有空白行:

awk '/./||p; {p=/./} END{if (p) print ""}'

I have a file -- a, and exist some continues blank line(more than one), see below:

cat a
1

2


3



4

5

So first I want to know if exist continues blank lines, I tried

cat a | grep '\n\n\n'

nothing output. So I have to use below manner

vi a 
:set list
/\n\n\n

So I want to know if exist other shell command could easily implement this? then if exist two and more blank lines I want to convert them to one? see below

1

2

3

4

5

at first I tried below shell

sed 's/\n\n\(\n\)*/\n\n/g' a

it does not work, then I tried this shell

cat a | tr '\n' '$' | sed 's/$$\(\$\)*/$$/g' | tr '$' '\n'

this time it works. And also I want to know if exist other manner could implement this?

解决方案

Well, if your cat implementation supports

   -s, --squeeze-blank
          suppress repeated empty output lines

then it is as simple as

$ cat -s a
1

2

3

4

5

Also, both -s and -n for numbering lines is likely to be available with less command as well.

remark: lines containing only blanks will not be suppressed.

If your cat does not support -s then you could use:

awk 'NF||p; {p=NF}'

or if you want to guarantee a blank line after every record, including at the end of the output even if none was present in the input, then:

awk -v RS= -v ORS='\n\n' '1'

If your input contains lines of all white space and you want them to be treated just like lines of non white space (like cat -s does, see the comments below) then:

awk '/./||p; {p=/./}'

and to guarantee a blank line at the end of the output:

awk '/./||p; {p=/./} END{if (p) print ""}'

这篇关于如何找到连续的空白行并将其转换为一条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆