0

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

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

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)
  • 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 – Isaac Dec 19 '18 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 '18 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. – Isaac Dec 20 '18 at 2:04
2

Try this awk

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.