1

So I try to replace blank space at the beginning of the line like so.

Original :

this
 is

\tsome
  text

What I want :

+this
+is
+
+some
+ text

I tried to use this regex to do that :

echo -e 'this\n is\n\n\tsome\n  text' |
perl -wpe 's/^\s?(.*)/+$1/'

But this is the result for that :

+this
+is
++some
+ text

So my line with no text at all is not processed correctly. Or rather, I don't understand why it behaves like that.

Any idea why ?

Thanks !

ogr
  • 610
  • 7
  • 23

2 Answers2

3

You are replacing the line-ending Line Feed. One solution is to remove it before the match and re-add it afterwards. This can be done using -l.

perl -ple's/^\s?/+/'

Alternatively, you could remove the Line Feed from the set of characters you are matching.

perl -pe's/^[^\S\n]?/+/'

If you're ok with also leaving VT, FF, CR, LINE SEPARATOR and PARAGRAPH SEPARATOR in place, you can shorten the above to the following:

perl -pe's/^\h?/+/'
ikegami
  • 367,544
  • 15
  • 269
  • 518
2

As pointed out by sticky bit in the comment, I just have to replace \s by \h. This is solved !

ogr
  • 610
  • 7
  • 23