Sublime Forum

Regex - Select the first line and the last line on file

#1

hi. I succeded to select the last line on the document

^(.*)$\z

BUT what is the regex to select the first line of the document?

1 Like

#2

\A(.*)$

(response must be longer than 10 characters)

1 Like

#3

yes, it is good , but If I want to replace that first line with something will not work. I need to do an insert, or to find the first line and to replace with something.

1 Like

#4

I FIND THE SOLUTION !

Search:
^\A(.*)$

1 Like

#5

now, TO INSERT SOMETHING BEFORE THE FIRST LINE (On the begining of the file)

Search:
^\A(.*)$

Replace By:
ANYTHING $1

or, another nice and simple regex solution. This will insert a new line at the beginning of file.

Search
(?s)(.*)

Replace by:
ANYTHING \r\n\1

1 Like

#6

same, TO INSERT SOMETHING AT THE END OF THE FILE, AFTER THE LAST LINE

Search:
^(.*)$\z

Replace by:
$1 ANYTHING

1 Like

#7

A full example:
\A(.+)$(?s:.*)^(.+)\Z will match the first and the last line in one go
a simple replacement of
\1\n\2
will strip everything except first and last lines.

\A(.+)$\n((?s).*)\n^(.+)\Z will match the first and last line, but you also have the rest of the contents
so a replacement of
\1\n\2\n\3
will reconstruct the original file.

In both cases replacing the backreferences or adding any content will amend the file. With these adding something before/after the first/last line is a very simple replacement, for example with the second one:
Insert before first line: ANYTHING\n\1\n\2\n\3
Insert after first line: \1\nANYTHING\n\2\n\3
Insert before last line: \1\n\2\nANYTHING\n\3
Insert after last line: \1\n\2\n\3\nANYTHING

Note for non-Sublime users: this regex requires multi-line mode due to the usage of ^ and $ inline.

0 Likes

#8

maybe a | in the middle of your regex will make a better solution

SEARCH: \A(.+)$(?s:.*)|^(.+)\Z

Replace by: ANYTHING \n\1\n\2 ANYTHING

same, in the second regex:

\A(.+)$((?s).*)|^(.+)\Z

0 Likes

#9

no, I deliberately went for a single straight regex where everything is available at once and it is one match, with the alternation you don’t have all the info available to you to have the flexibility, for example: swap first and list line is also a very simple replacement:
S: \A(.+)$\n((?s).*)\n^(.+)\Z
R: \3\n\2\n\1

See debugger: https://regex101.com/r/EAOe8G/1

0 Likes