YSC
YSC

Reputation: 40100

Replaces characters under condition

I'm looking for a regular expression to replace a group of spaces by the same number of dots on space groups which fulfill a certain condition.

Test case: replace spaces ending non "empty" lines with dots

TODO LIST:          |
==========          |
- item1             |
    * subitem1.1    |
    * subitem1.2    |
                    |
- item2             |
    * subitem2.1    |
    * subitem2.2    |
                    |
Some text... blah!  |

Should be transformed to (please note the space between items and ...):

TODO LIST:          |
==========          |
- item1 ............|
    * subitem1.1 ...|
    * subitem1.2 ...|
                    |
- item2 ............|
    * subitem2.1 ...|
    * subitem2.2 ...|
                    |
Some text... blah!  |

I've got the feeling I should use pre- and post-conditions, but I have no idea how. I use sed but perl would be ok.

Upvotes: 0

Views: 116

Answers (2)

Sundeep
Sundeep

Reputation: 23677

Another way to do:

$ perl -pe 's/^.*[^ ] (*SKIP)(*F)| /./g if /^\h*[*-]/' ip.txt 
TODO LIST:          |
==========          |
- item1 ............|
    * subitem1.1 ...|
    * subitem1.2 ...|
                    |
- item2 ............|
    * subitem2.1 ...|
    * subitem2.2 ...|
                    |
Some text... blah!  |

Upvotes: 3

Borodin
Borodin

Reputation: 126742

This will do as you ask. There's no need to cram everything into a single regex, so I first check to see if the line starts with possible spaces followed by a dash - or a star *, and then convert all trailing spaces apart from the first into the same number of dots . using an expression replacement

use strict;
use warnings 'all';

while ( <DATA> ) {

    s/\S[ ]\K([ ]+)/ '.' x length $1 /e if /^\s*[-*]/;

    print;
}

__DATA__
TODO LIST:          |
==========          |
- item1             |
    * subitem1.1    |
    * subitem1.2    |
                    |
- item2             |
    * subitem2.1    |
    * subitem2.2    |
                    |
Some text... blah!  |

output

TODO LIST:          |
==========          |
- item1 ............|
    * subitem1.1 ...|
    * subitem1.2 ...|
                    |
- item2 ............|
    * subitem2.1 ...|
    * subitem2.2 ...|
                    |
Some text... blah!  |

Upvotes: 4

Related Questions