テキストの書式設定 - コメント行の前に改行を挿入する

テキストの書式設定 - コメント行の前に改行を挿入する

クリーンアップする必要があるテキストがあります。基本的に、各コメントの前に改行を追加して、2行の間に空白行があるようにします。
参考のために修正が必要な内容の例は次のとおりです。

# quickly backup or copy a file with bash
cp filename{,.bak}
# Rapidly invoke an editor to write a long, complex, or tricky command
ctrl-x e
# Copy ssh keys to user@host to enable password-less ssh logins.
$ssh-copy-id user@host
# Empty a file
> file.txt
# Execute a command without saving it in the history
<space>command
# Capture video of a linux desktop
ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg
# Salvage a borked terminal
reset
# start a tunnel from some machine's port 80 to your local post 2001
ssh -N -L2001:localhost:80 somemachine
# Execute a command at a given time
echo "ls -l" | at midnight
# Query Wikipedia via console over DNS
dig +short txt <keyword>.wp.dg.cx
# currently mounted filesystems in nice layout
mount | column -t
# Update twitter via curl
curl -u user:pass -d status="Tweeting from the shell" http://twitter.com/statuse
s/update.xml
# Place the argument of the most recent command on the shell
'ALT+.' or '<ESC> .'
# output your microphone to a remote computer's speaker
dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp    

私はそれが次のように見えるようにしたいです:

# quickly backup or copy a file with bash
cp filename{,.bak}

# Rapidly invoke an editor to write a long, complex, or tricky command
ctrl-x e

# Copy ssh keys to user@host to enable password-less ssh logins.
$ssh-copy-id user@host

# Empty a file
> file.txt

# Execute a command without saving it in the history
<space>command

# Capture video of a linux desktop
ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg

# Salvage a borked terminal
reset

sed正しいフォーマットを得るためにOSXを試してみましたが、役に立ちませんでした。

sed 's/^\#/\n&/g' <filename.txt>

awkそれが問題を解決するより良い方法であれば、私はそれを使用することに反対しません。

ベストアンサー1

awk '{if (/^#/) {if (!n++ && NR>1) print ""} else n=0; print}'

で始まる一連の行の最初の行の前に空白行が挿入されます#。したがって、次のような入力のために:

xx
#1
#2
yy

以下を提供します。

xx

#1
#2
yy

nコメント行グループのコメント行数を数えます。print ""各コメント行グループの最初の行にある場合(そして最初の行除外入力を使用している場合)、空の行()を印刷しますNR>1

おすすめ記事