Sed - Replace all spaces at beginning of line with the number 1.
Does any one know what syntax i could use to allow me to replace all instances at the beginning of a line with ones.
Before : Code:
---------------------------------------------------------------------- Code:
---------------------------------------------------------------------- |
Code:
sed ':a; s/^\( *\) \([^ ]\)/\11\2/; t a' file |
Sounds like the sort of thing only a teacher would propose ...
|
I previously said 1`s as i thought i could just replace this with the HTML i needed.
What i actually require is that I replace each space at the beginning of the line with . Many Thanks, |
Hi,
sed ':a; s/^\( *\) \([^ ]\)/\1\ \2/; t a' file |
Quote:
|
Has anyone tested this?
With only a quick glance, it seems that it replaces "any number of spaces at the beginning of the line" with <newtext> each time thru the loop. |
@pixellany: Yes, I have and it works on my side.
I do believe this is based on greediness and works by taking the longest match, changing the last character with the desired match, then jump to the beginning and do it again (and again....), working your way back to the shortest, and last one. |
clank, grind, screeeech.....
(Trying to get brain to start......;) ) AHA!!! The logic is "any # of spaces" captured in the backref, and then ANOTHER space which gets replaced. Going thru the loop it keeps picking off one space at a time. BUT--when it's down to only one space, how does THAT one get replaced? |
@pixellany: ^\( *\) -> zero (!) or more followed by a space followed by a space at the beginning. Both \1 and \2 can be empty and thus the last space can be substituted as well.
BTW: I don't think the whole \2 part is needed: sed ':a; s/^\( *\) /\1\ /; t a' file seems to work too. EDIT The \2 part is needed in some cases and is the safe way to go, see post #12 by colucix END EDIT |
Saying it another way, when there is only 1 space, the second part of the regex gets it. clever!!
good news? Brain is started. bad news? This means I have to do my paying job......;) |
That's it: at each passage the loop substitutes one single space followed by a non-space character. The second reference is not actually needed, unless in the input there are lines containing only spaces that we don't want to replace. :jawa:
|
@colucix:
Quote:
Like pixellany already stated: Clever! |
All times are GMT -5. The time now is 02:38 AM. |