Reputation: 40100
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
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! |
if /^\h*[*-]/
only lines of interest^.*[^ ] (*SKIP)(*F)
this pattern (from start of line to last non-space character followed by space character) won't be changed
|
alternate pattern, these will be replaced with .
perl -i -pe
for in-place editingUpvotes: 3
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! |
TODO LIST: |
========== |
- item1 ............|
* subitem1.1 ...|
* subitem1.2 ...|
|
- item2 ............|
* subitem2.1 ...|
* subitem2.2 ...|
|
Some text... blah! |
Upvotes: 4