Matthew L. Abrasax Matthew L. Abrasax - 3 months ago 9
Perl Question

apply "backspace" to the line directly after the matching line perl

I'd like to re-format a text file such that the line immediately bellow the matching string gets cut and appended to the line with the matching string. Here is an example text:

Answer:
renice

X.
find / -name filename &
Y.
find / -name filename
Z.
bg find / -name filename


I'm looking for the end result:

Answer: renice

X. find / -name filename &
Y. find / -name filename
Z. bg find / -name filenames


I'm unable to get the following right trim suggestion:

$str =~ s/\s+$//;


To generate the result I need inline. The space is gone, but the string I need is still on the line bellow. The lines to cut and paste only occur directly bellow "Answer:" "X." "Y." or "Z."

mwp mwp
Answer

It would help to see your full solution, but here's a one-liner that does what you'd like:

perl -pe's/\s*$/ / if /^.+?[:.]/' 

This replaces any whitespace, including a newline, at the end of the string with a single space, but only if the pattern matches. The pattern looks for some characters at the beginning of the line followed by a period or colon. Add -i.bak to modify files in-place. Hope this helps!

Comments