Correct way to match a leading space with sed (all of them)?
Remove leading spaces: sed "s/^ *//"
Remove leading whitespace: sed "s/^[[:space:]]*//"
Remove leading spaces and tabs: sed "s/^[ \t]*//"
(works in GNU sed) or
sed 's/^[[:blank:]]*//'
(works with any sed
) or sed $'s/^[ \t]*//'
(in ksh/Bash/etc. to give a literal tab to sed
)
As said in the comments, the /g
specifier does nothing, as the beginning of line appears only once in the line, and even /g
does not retry the pattern more than one. You'd need to add a conditional branch explicitly to repeat the substitution: sed -e :a -e 's/^ //' -e ta
^ *
matches the empty string (no spaces) too, but that doesn't matter here. If you want to match lines that have at least one space, use ^ *
(double space) or ^ +
in extended regex. E.g. to change all indentations to exactly two spaces, use sed -e 's/^ */ /'
or sed -Ee 's/^ +/ /'
(-E
is supported in e.g. GNU and FreeBSD)
user9303970
Updated on September 18, 2022Comments
-
user9303970 over 1 year
How to match a leading space with
sed
(all of them)? I'm not talking about leading tabs, but rather only on leading spaces.From a small test I did in Nano this seems to be correct:
sed "s/^ //g"
Do you find something wrong with this method?
Note: "All of them" means all leading spaces in the document, in case there are 2 or more, and not just one.
-
RomanPerekhrest about 6 years
tab
is also INwhitespace
category.sed "s/^[[:space:]]//g"
-
user9303970 about 6 years@RomanPerekhrest So I should go through a paradigm change --- from now and long I shall say "space" for a simple space as with the SPACE key in my keboard and "whitespace" for any space in the general sense (space or tabulation), correct?
-
-
Stéphane Chazelas about 6 yearsNote that
sed "s/^[ \t]*//"
works in GNUsed
only ifPOSIXLY_CORRECT
is not in the environment. Otherwise it stripst
s and backslashes like othersed
implementations. -
Oscar Zhang over 2 yearsI wonder what's difference btw spaces and whitespace by definition and why are they treated differently? In some case,
sed "s/^ *//"
just works if I have one space, while in other case, say I extract the righthand side of a diff output(after|<>
), I have to use 2nd onesed "s/^[[:space:]]*//"
to do the job. -
ilkkachu over 2 years@OscarZhang, tabs and newlines are "whitespace" too, in addition to the space I get from the big wide button.
sed "s/^ *//"
removes just spaces, not tabs etc.[[:blank:]]
would match spaces and tabs and[[:space:]]
matches some other stuff too, even newlines (not that you'd see that easily with sed or grep)