ファイル内の各既存の行の上に新しい行を追加します。

ファイル内の各既存の行の上に新しい行を追加します。

次の行を含むファイルがあります

This is an PLUTO
This is PINEAPPLE
This is ORANGE
This is RICE

各行の上に新しい行を作成し、次のように新しい行出力に最後の文字列を挿入するにはどうすればよいですか?

PLUTO:
This is an PLUTO
PINEAPPLE:
This is an PINEAPPLE
ORANGE:
This is an ORANGE
RICE:
This is an RICE

ありがとう

ベストアンサー1

awk行自体を印刷する前に、コロンが続く各行の最後のフィールドを印刷するために使用されます。

$ awk '{ print $NF ":"; print }' file
PLUTO:
This is an PLUTO
PINEAPPLE:
This is PINEAPPLE
ORANGE:
This is ORANGE
RICE:
This is RICE

単一printステートメントを使用しますが、レコード区切り文字(改行)と(行)を明示的に印刷する$0バリアントです。

awk '{ print $NF ":" ORS $0 }' file

さまざまな用途printf

awk '{ printf("%s:\n%s\n", $NF, $0) }' file

使用sed:

$ sed 'h; s/.* //; s/$/:/; G' file
PLUTO:
This is an PLUTO
PINEAPPLE:
This is PINEAPPLE
ORANGE:
This is ORANGE
RICE:
This is RICE

注釈付きsedスクリプト:

h;          # Copy the pattern space (the current line) into the hold space (general purpose buffer)
s/.* //;    # Remove everything up to the last space character in the pattern space
s/$/:/;     # Add colon at the end
G;          # Append the hold space (original line) with an embedded newline character
            # (implicit print)

おすすめ記事