最後の例として,空白行をまとめるcat -sと同じ機能を実装している,
複雑さと速度を上げていく三つのスクリプトを以下に書きます.
最初のものは,最初に空白行を取り去り,まだ残っていれば最後に取り去りま す.
#!/usr/bin/sed -f
# on empty lines, join with next
# Note there is a star in the regexp
:x
/^\n*$/ {
N
bx
}
# now, squeeze all '\n', this can be also done by:
# s/^\(\n\)*/\1/
s/\n*/\
/
以下のものはより複雑で,最初にすべての空の行を取り除きます.まだ残って いる場合,最後に単一の空白行を取り去ります.
#!/usr/bin/sed -f
# delete all leading empty lines
1,/^./{
/./!d
}
# on an empty line we remove it and all the following
# empty lines, but one
:x
/./!{
N
s/^\n$//
tx
}
以下は,前置および後置されている空白行を取り除きます.それは最も速いも
のです.sedが行の終りで自動的にスクリプトの最初のサイクルに戻
るという事実を利用することなく,nとbを用いて複雑なループ
を実行していることに注意してください.
#!/usr/bin/sed -nf
# delete all (leading) blanks
/./!d
# get here: so there is a non empty
:x
# print it
p
# get next
n
# got chars? print it again, etc...
/./bx
# no, don't have chars: got an empty line
:z
# get next, if last line we finish here so no trailing
# empty lines are written
n
# also empty? then ignore it, and get next... this will
# remove ALL empty lines
/./!bz
# all empty lines were deleted/ignored, but we have a non empty. As
# what we want to do is to squeeze, insert a blank line artificially
i\
bx