トークンで区切られたSedマージライン

トークンで区切られたSedマージライン

サンプル文書を生成するために、sedを使用してテキストファイルの行を処理するスクリプトを作成しようとしています。ほとんどのスクリプトは動作しますが、極端な状況に直面しました。次のドキュメントを検討してください

line-1
line-2, part2
line-3-should-be-a-very-long,
    line-3-continued
line-4

問題は、一部(すべてではない)行が特殊トークン(カンマで表される)で終わるということです。このフラグは、1つの長い行を生成するためにこの行を次の行に関連付ける必要があることを示します。

したがって、私の例では、toを私にline-3-should-be-a-very-long,リンクする必要があります(コンマを維持したい)。 2行目には行末ではなくカンマが含まれていますが、特別な操作はありません。line-3-continuedline-3-should-be-a-very-long, line-3-continued

残りの処理は、いくつかのコマンドsedとコマンドを一緒にgrepパイプすることによって実行されるため、sedソリューションは完全にフィットします。

ベストアンサー1

$ sed '/,$/{N;s/\n//;}' file
line-1
line-2
line-3-should-be-a-very-long,    line-3-continued
line-4

スペースを削除する必要がある場合:

$ sed '/,$/{N;s/\n[[:blank:]]*//;}' file
line-1
line-2
line-3-should-be-a-very-long,line-3-continued
line-4

(行の間にスペースを入れるには、//コードでそれを置き換えます/ /。)

行が複数回連続できる場合

line-1
line-2
line-3-should-be-a-very-long,
    line-3-continued,
        line-3-continued-further
line-4

次に、

$ sed '/,$/{:loop;N;s/\n[[:blank:]]*//;/,$/bloop;}' file
line-1
line-2
line-3-should-be-a-very-long,line-3-continued,line-3-continued-further
line-4

最後のsedスクリプトはコメントとともに説明されます。

/,$/{                     # if the current line ends with a comma, then...
    :loop                 # define label "loop"
    N                     # append next line from input (a newline will be inserted in-between)
    s/\n[[:blank:]]*//    # delete that newline and any blanks (tabs or spaces) directly after it
    /,$/bloop             # if the line now ends with comma, branch to the "loop" label
}
# implicit output of (possibly) modified line at end

おすすめ記事