![在文件中每个现有行上方添加新行](https://linux22.com/image/143481/%E5%9C%A8%E6%96%87%E4%BB%B6%E4%B8%AD%E6%AF%8F%E4%B8%AA%E7%8E%B0%E6%9C%89%E8%A1%8C%E4%B8%8A%E6%96%B9%E6%B7%BB%E5%8A%A0%E6%96%B0%E8%A1%8C.png)
我有一个包含以下几行的文件
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