Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

shell - how to find continuous blank lines and convert them to one

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 '


'

nothing output. So I have to use below manner

vi a 
:set list
/



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/

(
)*/

/g' a

it does not work, then I tried this shell

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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='

' '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 ""}'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...