user2433705
user2433705

Reputation: 151

Merging lines in Notepad++ or by using Python

I have a long file which is structured like below:

What I want to do:

How I can easily do it in python (2.7)?

Regex in Notepad++ may also work. I've heard that I should use a multi-line mode but I don't know how to do it. Probably it's not even hard but I have a hard time dealing with it.

Thanks.

Here the input (simplified):

;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU”
;”     6,291.00”;;
;500;6900;;”YPNV”;”KE”;”53213072”;”YOU”
;”     6,991.00”;;

screenshot Notepad++

Expected output:

;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU”;;”     6,291.00”;;
;500;6900;;”YPNV”;”KE”;”53213072”;”YOU”;;”     6,991.00”;;

Upvotes: 0

Views: 98

Answers (3)

Srdjan M.
Srdjan M.

Reputation: 3405

Regex: \n^(?!;500)

Details:

  • ^ Asserts position at start of a line
  • (?!) Negative Lookahead

Python code:

text = open(r'C:\....txt').read()
r = re.compile(r'\n^(?!;500)', re.M)
text = r.sub(';', text)

Output:

;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU”;;”     6,291.00”;;
;500;6900;;”YPNV”;”KE”;”53213072”;”YOU”;;”     6,991.00”;;

Demo code

Upvotes: 0

Jean-Francois T.
Jean-Francois T.

Reputation: 12930

Use Notepad++ for this kind of simple changes.

  1. Go to Replace menu (Ctrl+H)
  2. Select Regular expressions (Alt+G)
  3. Enter following values:

    • Find what: [\r\n]+(;(?!500))
    • Replace with: \1
  4. Click on Replace All (Alt+A)

Upvotes: 0

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this regex:

[\r\n]+(?!;500)

Replace each match with a ;

Click for Demo

Explanation:

  • [\r\n]+ - matches 1+ occurrences of either a newline character or a carriage return
  • (?!;500) - negative lookahead to make sure that the current position is not followed by :500

Before Replacing:

enter image description here

After replacing:

enter image description here

Upvotes: 1

Related Questions