Correct way to match a leading space with sed (all of them)?

6,650

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)

Share:
6,650
user9303970
Author by

user9303970

Updated on September 18, 2022

Comments

  • user9303970
    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
      RomanPerekhrest about 6 years
      tab is also IN whitespace category. sed "s/^[[:space:]]//g"
    • user9303970
      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
    Stéphane Chazelas about 6 years
    Note that sed "s/^[ \t]*//" works in GNU sed only if POSIXLY_CORRECT is not in the environment. Otherwise it strips ts and backslashes like other sed implementations.
  • Oscar Zhang
    Oscar Zhang over 2 years
    I 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 one sed "s/^[[:space:]]*//" to do the job.
  • ilkkachu
    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)