awkは最初の文字の後に余分なスペースを削除しますか?

awkは最初の文字の後に余分なスペースを削除しますか?

awkは最初の文字の後に余分なスペースを削除しますか?

私たちのファイルは次のとおりです。

Blue    sky.    Nice       weather.
    White cloud.    Bright    sun.
        Cool air. Bla    bla          bla.

次のようなものを入手するには:

Blue sky. Nice weather.
    White cloud. Bright sun.
        Cool air. Bla bla bla.

このコマンドは、余分なawk '{$1=$1} 1' fileスペースをすべて削除します。
しかし、最初の文字の後にある余分なスペースを削除するだけです。

知っている人はいますか?
興味を持ってくれてありがとう!

ベストアンサー1

Linuxを実行していてGNU Sedがある場合は、g代替コマンドにこのフラグと番号を使用できますs

sed -r 's/ +/ /g2' file.txt

引用するにはinfo sed

 Note: the POSIX standard does not specify what should happen when
 you mix the `g' and NUMBER modifiers, and currently there is no
 widely agreed upon meaning across `sed' implementations.  For GNU
 `sed', the interaction is defined to be: ignore matches before the
 NUMBERth, and then match and replace all matches from the NUMBERth
 on.

ただし、空白の最初のインスタンス(前に空白がない場合)を実際に変更したい状況があるため、完全な答え(GNU Sedを使用)は次のようになります。

sed -r 's/^/ /;s/ +/ /g2;s/^ //' file.txt

つまり、すべての行に先行スペースを追加し、最初のスペースを除く連続スペースのすべてのインスタンスを「圧縮」してから、追加された先行スペースを削除します。


先行スペースが常に8の倍数の場合は、次のPOSIX互換コマンドを使用できます。

unexpand file.txt | sed 's/  */ /g' | expand

またはより簡単に:

unexpand file.txt | tr -s ' ' | expand

おすすめ記事