Petra Barus
Petra Barus

Reputation: 4013

Replace Newline And Following Whitespaces Until A Specific String In A File

How can I replace newline and following whitespaces until a specific string using one-liner sed or perl?

e.g. I want to replace newline and following whitespaces before a string 'XYZ' in a file. All line starting with word 'XYZ' will be appended before previous line (with one extra whitespace).

lorem ipsum dolor sit amet
  XYZ lorem ipsum dolor sit amet
    XXX lorem ipsum dolor sit amet
  DDD lorem ipsum dolor sit amet
      XYZ lorem ipsum dolor sit amet
cccc lorem ipsum dolor sit amet

   XYZ lorem ipsum dolor sit amet

the output will be

lorem ipsum dolor sit amet XYZ lorem ipsum dolor sit amet
    XXX lorem ipsum dolor sit amet
  DDD lorem ipsum dolor sit amet XYZ lorem ipsum dolor sit amet
cccc lorem ipsum dolor sit amet XYZ lorem ipsum dolor sit amet

Upvotes: 2

Views: 179

Answers (2)

ikegami
ikegami

Reputation: 385897

perl -0777pe's/\n\s*(?=XYZ)/ /g' file

-0777 causes the entire file to be considered one line.

The command as written will output to STDOUT, which you can redirect as you please. -i~ and -i will edit "in place", with and without backup respectively.

Upvotes: 5

Krishnachandra Sharma
Krishnachandra Sharma

Reputation: 1342

Try this:

s/[\s\n]+XYZ/ XYZ/gsm;

Upvotes: 0

Related Questions