How can I change the last character of x lines?

73 views Asked by At

I have a text with 500 lines, I want to take the last character of every 10 lines and change it to a semicolon symbol without changing the content of the rest of the lines. What you should do is change 50 lines and add to all of them; at the end changing the last character (whatever it is) for a semicolon.

Example:

line1'
line2{
line3+
line4ยด

If I apply the logic that I have proposed above, for every second line it should look like this:

line1'
line2;
line3+
line4;

I want to do it only using Regex, without programming languages or similar.

My Regex:

^(.*\r?\n){9}(.*)(.)$
1

There are 1 answers

1
The fourth bird On

In your pattern you have 3 capture groups, where you can also just use 1 capture group. But what you should not do is repeat the capture group itself, as you would then only capture the value of the last iteration.

Using ^(.*\r?\n){9} you would then only capture the 9th line, and you would lose the first 8 lines when you only use the capture groups in the replacement.

You can use a single capture group, and within that group you can match 9 lines ending on a newline and then then 10th line.

After the capture group you can match a single character. Note that the . matches any character, and it will not match if the 10th line is empty.

^((?:.*\r?\n){9}.*).$

See a regex demo

In the replacement use group 1 followed by a semicolon often denoted as $1; or \1;