remove white space in bash using sed remove white space in bash using sed bash bash

remove white space in bash using sed


To remove all the leading blanks, use:

sed 's/^ *//g'

To remove all leading white space of any kind:

sed 's/^[[:space:]]*//g'

The ^ symbol matches only at the beginning of a line. Because of this, the above will leave alone any whitespace not at the beginning of the line.


Breaking down your current sed pattern 's/ */ /g':The search pattern, ' *', matches a single space, followed by zero or more spaces. The replacement pattern, ' ', is a single space. The result is to find any set of one or more spaces and replace it by a single space, hence removing all but one of the spaces. To make it remove all, you can just make your replacement pattern the empty string, '': sed 's/ *//g'

Note, however, that the 'g' makes it global, so that will also remove the space between the number and the file path. If you just want to remove the leading space, you can just drop the g. You can also use the + quantifier, which means "at least one", instead of the *, which means "at least zero".That would leave you with: sed 's/ \+/'

ETA: As John1024 points out, you can also use the ^ anchor to specify the beginning of the line, and the \s wildcard to specify any whitespace characters instead of just spaces: sed 's/\s\+//'