Chuck Zhu
Chuck Zhu

Reputation: 9

Add a new line with specific pattern before a matched pattern in Notepad++

I have a csv file and I would like to reform it. I like to add a new line with "M19" before every line with characters "M06".

Before:

T40400010
M06
(T40400010, 5.0MM SOLID CARBIDE REAMER - 6FL)

After reforming:

T40400010
M19
M06
(T40400010, 5.0MM SOLID CARBIDE REAMER - 6FL)

I am planning to solve this using regular expression in python, but i also i open to other solutions. Thanks.

Upvotes: 1

Views: 56

Answers (3)

dawg
dawg

Reputation: 103844

You can do:

import re 

with open(fn) as f:
    for line in f:
        if re.search(r'^M06$', line):
            print('M19')
        print(line) 

Prints:

T40400010
M19
M06
(T40400010, 5.0MM SOLID CARBIDE REAMER - 6FL)

If you want the M19 after the M06 just move the print(line) above the if re.search(r'^M06$', line): rather than below.


If you want to have the effect of 'editing' the file, and the file is a reasonable size (ie, easily fits in memory) you can do:

import re 

with open(fn) as f:
    data=re.sub(r'^(M06)$', r'M19\n\1', f.read(), flags=re.M)       

with open(fn, 'w') as f:
    f.write(data)   

If you have a file larger than what you want in memory, you can do:

import re, tempfile, shutil

with open(fn, 'r') as f_in, tempfile.NamedTemporaryFile(mode='w', delete=False) as f_out:
    tmp_name=f_out.name
    for line in f_in:   
        if re.search(r'^M06$', line):
            print('M19\n',end='', file=f_out)   
        print(line,end='', file=f_out)  

shutil.move(tmp_name, fn)   

Upvotes: 3

RToyo
RToyo

Reputation: 2877

You can do this in Notepad++ by doing a search with this expression:

^(M06)$

And replacing it with:

M19\n\1

The \n character represents a new line, and \1 represents the reference to the "M06" value in the brackets of the regular expression. Anything in the brackets (in this case, "M06") will be captured, and returned as \1.

The reason I used the reference to a capture group, instead of just replacing it with "M19\nM06", is because you may want to alter the expression to find more data. For example, if there is other data on the M06 line, you might want to look for an expression like this:

^(.*M06.*)$

Edit: Patrick beat me to the answer. I'm leaving this up, just for the addition of the capture group.

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51653

You can use Notepad++ buildin search+replace dialog (Strg+H for me).

Search for the regex ^M06$ and replace it with M19\r\nM06 (use \n if on unix, \r\n is windows).

Make sure to choose the Regular expression option.

If you really want to have a newline between those two, double up on \r\n

Search and replace dialog

Upvotes: 1

Related Questions