how to select every nth line and swap every consecutive lines up to next mth line in notepad++

StackOverflow https://stackoverflow.com/questions/23668468

  •  23-07-2023
  •  | 
  •  

Question

I have some large text files containing data like below:

    2.086
    0.019
    2.181
    0.004
    2.308
    0.005
    2.165
    0.023
    2.113
    0.004
    2.022
    0.005
    0.013
    0.033
    0.005
    0.026
    0.009
    0.037

I would like select every 13th line and swap the consecutive lines with one another up to the 18th line. The required output should be like below:

    2.086
    0.019
    2.181
    0.004
    2.308
    0.005
    2.165
    0.023
    2.113
    0.004
    2.022
    0.005
    0.033
    0.013
    0.026
    0.005
    0.037
    0.009

I was trying to construct a suitable regex for this operation but not sure how to start with selecting every 13th to 18th line !!

Was it helpful?

Solution

EDIT: After discussion in comments and in chat, here is the solution first. The explanation follows.

Search: (([^\n]*\n){12})((?2))((?2))((?2))((?2))((?2))((?2))

Replace: \1\4\3\6\5\8\7

Explanation

Here the general recipe for selecting 5 lines:

(?:[^\n]*\n){5}

See demo

The [^\n]*\n selects any number of non-newline characters, followed by a newline character. We do that 5 times. You can add anchors, lookarounds and so on to do more.

For instance, this regex swaps the first 3 lines with the next 5:

\A((?:[^\n]*\n){3})((?:[^\n]*\n){5})

The key to understand here is that groups of lines are captured to Groups 1 and 2. This is done by enclosing each expression in capturing parentheses. Later, in the replacement, as the demo shows, these groups can be referenced by their number like so: \1 for Group 1, and so on.

See demo

You want to target the 13th line? Match 12, then 1. You want to do something with further lines? Add lines, and switch the capture groups around as needed.

\A((?:[^\n]*\n){12})((?:[^\n]*\n))((?:[^\n]*\n){2})

In this example, the first group of parentheses captures 12 lines, the next captures the 13th line, the next captures the following two lines. You can switch the 13th and the following two lines by rearranging the groups in the replacement: \1\3\2

You want to do this multiple times in a file? Don't anchor. Here is a demo that swaps every 5th line with lines 6 and 7.

Just adjust to your needs.

EDIT

Based on your comments, this should do exactly what you need.

Search: ((?:[^\n]*\n){12})((?:[^\n]*\n))((?2))((?2))((?2))((?2))((?2))

Replace: \1\3\2\5\4\7\6

Demo

Same idea. The ((?2)) is a way to avoid repeating the same regex over and over (the second group of capturing parentheses, which captures one line). (?2) says "repeat the expression in Group 2", and the extra parentheses put these expressions into groups 3, 4, 5, 6, 7.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top