I'd like to replace the leading space or tab characters on each line of a file with a like-number of other characters (let's use _ for simplicity).
E.g.
foo bar
foo bar
line 3
becomes
foo bar
_foo bar
__line 3
Note that non-leading whitepsace is not affected, otherwise this would be easy! I suspect it's still easy, but I'm missing the trick.
This will work for you:
sed ':a;s/^\([[:space:]]*\)[[:space:]]/\1_/;ta' file
$ sed ':a;s/^\([[:space:]]*\)[[:space:]]/\1_/;ta' <<<$'foo bar\n foo bar\n\t\tline 3\n _ x'
foo bar
_foo bar
__line 3
__ x
Are you O.K. with a Perl one-liner? You can write:
perl -pe 's/^([ \t]+)/"_" x length $1/e'
(either piping in your file on standard-input, or specifying a filename at the end of the cmomand).
Edited to add: William Pursell, in a comment above, asks whether you want "a tab get replaced with a single '_', or enough to fill out a tabstop". The above command would replace a tab with a single underscore. If you want enough to fill out a tabstop, the simplest approach is to use the expand utility, which converts tabs to spaces, before passing the input to Perl:
expand -i | perl -pe 's/^([ \t]+)/"_" x length $1/e'
(either piping in your file on standard-input, or specifying a filename at the end of the expand part, just before the | character).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With