Replacing strings based on line numbers
-
Dear Notepad++ users!
I have a simple task and a simple question, but I can’t get a simple answer) (maybe I’m not formulating the request so precisely in either Russian or English). The point is this. How can I automate such a routine task as copying one line in a text file and replacing another line with it. I usually do this between two txt files, but it can be done in one. So, for example, I need to replace 1 line with the 4th, 2nd with the 5th, 3rd with the 6th, etc. Regardless of the content of the lines. In other words, is it possible to somehow do automatic line-by-line replacement based on line numbers?
-
@Evgenii-Baranov
Not entirely clear to me. From your description, it seems like all lines except the last three are shifted upwards to replace the earlier lines. However, could you possibly give a few more examples to illustrate this better? This is how I understand the result based on the information provided:Line 1: This is line 4 before replacing. Line 2: This is line 5 before replacing. Line 3: This is line 6 before replacing. Line 4: This is line 7 before replacing. Line 5: This is line 8 before replacing. Line 6: This is line 9 before replacing. Line 7: This is line 10 before replacing. Line 8: This is line 11 before replacing. Line 9: This is line 12 before replacing. Line 10: This is line 10 before replacing. Line 11: This is line 11 before replacing. Line 12: This is line 12 before replacing.
-
Hello, @evguenii-baranov and All,
Quite easy with regular expression !
So, let’s suppose that your file contains only the simple text, below :
This is a very small bunch of text to see if it works nicely
-
Open your file in Notepad++
-
Place the caret ( cursor ) on the first line which must be replaced ( Line
This is
). This point is IMPORTANT ! -
Open the Replace dialog (
Ctrl + H
) -
Un-check all the box options ( IMPORTANT )
-
SEARCH
(?-is).+\R(?=(?:.+\R){2}(.+\R))
-
REPLACE
$1
-
Select the
Regular expression
search mode -
Click ONCE only on the
Replace All
button
=> You should get your expected text :
of text to see if it works nicely to see if it works nicely
Then, you just have to get rid of the three last lines which are repeated :
of text to see if it works nicely
In a general way, if you must replace the first line by the line
N
, use the following generic regex :-
SEARCH
(?-is).+\R(?=(?:.+\R){
N-2}(.+\R))
-
REPLACE
$1
And replace the
N-2
expression with its appropriate number !so, for example, the different regex searches, below, may be used :
-
(?-is).+\R(?=(?:.+\R){0}(.+\R))
-
(?-is).+\R(?=(?:.+\R){1}(.+\R))
-
(?-is).+\R(?=(?:.+\R){5}(.+\R))
Best Regards,
guy038
-