在文件中每个现有行上方添加新行

在文件中每个现有行上方添加新行

我有一个包含以下几行的文件

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)

答案2

试试这个 awk

awk '{$0=$NF":\n"$0}1' file

相关内容