deleting some empty lines with sed

Kris Stephens [Hail Eris!] krs at uts.amdahl.com
Sun May 5 06:27:36 AEST 1991


How about this:

	:
	# sh or ksh
	#
	# Reduce all multiple consecutive "empty" lines to singles.  Process
	# stdin (switch it to filename processing or either as you wish).
	#

	# Make the T in the sed line a <TAB> char.  I leave it a T for
	# this posting just for clarity.

	# Use sed to strip all trailing blanks and tabs
	sed 's/[ T]*$//' |

	# Use awk to delete empty lines that follow empty lines
	awk '
		$0 != "" {
			print
			prevnull = 0
			next
		}

		prevnull == 0 {
			print
			prevnull = 1
		}' -

The flow in the awk script is to look for non-null lines first on the
assumption that more input lines will be non-null than null.  If a line
is non-null, print it and set the null-marker off.  No need to test the
marker variable before setting it, that would take longer than simply
making the assignment every time.

If we get past that first block, we are processing a null line.  If the
null-marker is off, print this null line and set the null-marker on.  Any
line not matching one of these two blocks is a null line following a null
line, and is ignored.

This is a pretty standard approach for me to take.  I use sed to do editing
of an input-stream for awk, where I do the conditional work based on line
contents.  Since sed is faster than awk, the sed process typically writes
the data out faster than awk will take it in, so doing the line-editing in
sed instead of within the awk script is no performance penalty at all for
the shell script as a whole.  It is, in fact, a performance gain because
the awk script would take more time if I expanded its definition of a null
line to include blanks and tabs.

...Kris
-- 
Kristopher Stephens, | (408-746-6047) | krs at uts.amdahl.com | KC6DFS
Amdahl Corporation   |                |                    |
     [The opinions expressed above are mine, solely, and do not    ]
     [necessarily reflect the opinions or policies of Amdahl Corp. ]



More information about the Comp.unix.shell mailing list