
ファイルの余分なスペースを置き換えるためにsedコマンドを作成しようとしています。各単語の間には1つのスペースしかありませんが、先頭のスペースとタブはそのままにしてください。したがって、ファイルは次のようになります。
This is an indented paragraph. The indentation should not be changed.
This is the second line of the paragraph.
になります:
This is an indented paragraph. The indentation should not be changed.
This is the second line of the paragraph.
私が試したバリエーション
/^[ \t]*/!s/[ \t]+/ /g
どんなアイデアでも大いに感謝します。
答え1
$ sed 's/\>[[:blank:]]\{1,\}/ /g' file
This is an indented paragraph. The indentation should not be changed.
This is the second line of the paragraph.
私が使用する式は1つ以上[[:blank:]]
(スペースまたはタブ)と一致します。一文の後ろに、空白に置き換えます。\>
単語文字と単語以外の文字の間の幅がゼロの境界と一致します。
これはOpenBSDでデフォルトでテストされていますが、sed
GNUでも動作する必要があると思います。sed
GNUは単語の境界を一致させるsed
ためにも使用されます。\b
sed -E
次のように短縮することもできます。
sed -E 's/\>[[:blank:]]+/ /g' file
繰り返しますが、\>
GNUが機能しない場合はsed
代わりに使用してください\b
。
上記はサンプルテキストを正しい方法でソートしますが、そうではありません。かなり最初の文の後のように、句読点の後のスペースを削除するために使用されます。
This is an indented paragraph. The indentation should not be changed.
This is the second line of the paragraph.
これを行うには、少し複雑なバリエーションがトリックを実行します。
$ sed -E 's/([^[:blank:]])[[:blank:]]+/\1 /g' file
This is an indented paragraph. The indentation should not be changed.
This is the second line of the paragraph.
これは、空白以外の文字の後に1つ以上の空白文字が続くものを、空白以外の文字と空白に置き換えます。
または標準を使用してくださいsed
(存在する場合にのみ置き換えられるため、非常に小さな最適化)。複数スペース/タブではなく部分の後にスペース/タブがあります)、
$ sed 's/\([^[:blank:]]\)[[:blank:]]\{2,\}/\1 /g' file
This is an indented paragraph. The indentation should not be changed.
This is the second line of the paragraph.
答え2
POSIX的に:
sed 's/\([^[:space:]]\)[[:space:]]\{1,\}/\1 /g; s/[[:space:]]*$//'
空白以外の空白の後に続く1つ以上の空白文字シーケンスを対応する空白ではないSPC文字に置き換えて、末尾の空白文字を削除します。その後、空白行と行を末尾のスペースで上書きします(Microsoftの末尾のテキストファイルを含む)。線)。