重複記号の削除と線の調整

重複記号の削除と線の調整

正確には、次のテキストファイル(test.txt)があります(インスタンスごとに同じ数のオプション)。

# a comment

first: info about first:  option1 \
                          option2 \
                          option3

second: info about second: option1 \
  option2 \
  option3

#third: info about third: option1 \
#                         option2 \
#                         option3

fourth: info about fourth: option1 \
                           option2 \
                           option3 \

テキストを次のように再構成したいと思います。

a comment first: info about first: option1 option2 option3 
second: info about second: option1 option2 option3 
third: info about third: option1 option2 option3 
fourth: info about fourth: option1 option2 option3

ベストアンサー1

単一のsedプログラムを使用する:

sed -E '
    # remove leading comment chars
    s/^[[:blank:]]*#+[[:blank:]]*//

    # label "a" for branching
    :a
    # if trailing slash:
    /\\$/ {
        # read next line
        N
        # remove backslash, newline, leading whitespace and comment char 
        s/\\\n[[:blank:]]*#*[[:blank:]]*/ /
        # branch to label "a"
        ba
    }

    # remove blank lines
    /^[[:blank:]]*$/d
' test.txt

しかし、Perlは非常にコンパクトです。段落()を読み、段落の各行から先行スペースと-00コメント文字(/mおよび修飾子)を置き換えて、末尾のバックスラッシュ改行文字を削除します。/g

perl -00 -lanE 's/^\s*#*\s*//mg; s/\\(?:\Z|\n)/ /g; say' test.txt

おすすめ記事