1

I have a file with below lines

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

How do I make a new line above each lines and insert the last string to the new line output as below:

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

Thanks

1
  • Just for consistency's sake, where did the "an" come from (or disappear from) on the last 3 lines?
    – Jeff Schaller
    Jan 4, 2019 at 1:28

2 Answers 2

5

Using awk to print the last field of each line followed by a colon before printing the line itself:

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

Variation that uses a single print statement but that explicitly prints the output record separator (a newline) and $0 (the line):

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

Variation using printf instead:

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

Using sed:

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

Annotated sed script:

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)
3
  • With only one s/// command, no hold copy, portable way to add a newline sed solution: sed 'G; s/\(.*\) \(.*\)\(\n\)$/\2:\3\1 \2/' inf1
    – user232326
    Dec 19, 2018 at 1:17
  • @Isaac Your sed code appears to require at least one space on the line to be able to insert the colon.
    – Kusalananda
    Dec 19, 2018 at 6:39
  • If that is a problem (which the wording of the question suggests it isn't) you may use this script instead: sed -E 'G;s/(.*)(\b[^ ]+)(\n)/\2:\3\1\2/' file.
    – user232326
    Dec 20, 2018 at 2:04
2

Try this awk

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .