Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace leading whitespace with sed (or similar)

Tags:

regex

bash

unix

sed

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.

like image 922
BeeOnRope Avatar asked Dec 18 '25 22:12

BeeOnRope


2 Answers

This will work for you:

sed ':a;s/^\([[:space:]]*\)[[:space:]]/\1_/;ta' file

Example

$ 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
like image 181
SiegeX Avatar answered Dec 21 '25 20:12

SiegeX


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).

like image 33
ruakh Avatar answered Dec 21 '25 18:12

ruakh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!