Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl/regex to remove first 3 lines and last 3 lines of a string

I was looking to build a regex statement to always remove the first 3 lines of the string, and last 3 lines of the string (the middle part could be any n number of lines content). Any clean regex way to acheive this output? (i.e. always strip our first 3 lines and last 3 lines of the string - and preserve the middle part, which could be a variable # of lines)

Thanks.

e.g.

Input String:

"
1
2
3
<1...n # of lines content>
4
5
6
"

To desired output string:

"<1..n # of lines content>"
like image 742
simbatish Avatar asked Aug 12 '11 23:08

simbatish


People also ask

How do I remove the first few characters in a string in Perl?

How can I achieve this in perl regex? Do you want to remove the first 3 characters or do you want to remove the specific KP_ prefix. There is a difference. you can use substring method for that.

How do I match multiple lines in Perl?

Solution. Use /m , /s , or both as pattern modifiers. /s lets . match newline (normally it doesn't). If the string had more than one line in it, then /foo.

How do I remove a carriage return in Perl?

Removing carriage returns Carriage returns and linefeeds are removed by combining \r and \n in that order, of course, since that's the order in which they appear in text files, like those that are created on Windows systems.

How do I remove a character from a string in Perl?

The chop() function in Perl is used to remove the last character from the input string.


1 Answers

The previously given solutions are really complex! All one needs is

s/^(?:.*\n){1,3}//;
s/(?:.*\n){1,3}\z//;

If you want to accept a lack of trailing newline at the end, you can use

s/\n?\z/\n/;
s/^(?:.*\n){1,3}//;
s/(?:.*\n){1,3}\z//;

or

s/^(?:.*\n){1,3}//;
s/(?:.*\n){0,2}.*\n?\z//;
like image 163
ikegami Avatar answered Sep 28 '22 14:09

ikegami