Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...