2

This bash script is supposed to remove leading whitespace from grep results:

#!/bin/bash
grep --color=always $@ | sed -r -e's/:[[:space:]]*/:/'

But it doesn't match the whitespace. If I change the substitution text to "-", that shows up in the output, but it still never removes the whitespace. I've tried it without the "*", escaping the "*", with "+", etc, but nothing works. Does anyone know why not?

(I'm using sed version 4.2.1 on Ubuntu 12.04.)


Thanks all, this is my modified script, which shows grep color and also trims leading blanks:

#!/bin/bash
grep --color=always $@ | sed -r -e's/[[:space:]]+//'
Byron Hawkins
  • 2,536
  • 2
  • 24
  • 34

4 Answers4

6

You need to remove the --color option for this to work. The color codes confuse sed:

grep  $@ | sed -r -e's/:[[:space:]]*/:/'
perreal
  • 94,503
  • 21
  • 155
  • 181
  • +1 - Awesome. Deleting my answer. Learn something new every day. – Buggabill Sep 07 '12 at 19:51
  • @MichaelFoukarakis Because there isn't actually a `:[[:space:]]` in the output of `grep --color` -- instead there's a bunch of `\033[` escape sequences (may vary by terminal) in there, for coloring. – ephemient Sep 07 '12 at 19:54
2

The color information output by grep takes the form of special character sequences (see answers to this StackOverflow question), so if the colon is colored and the whitespace isn't, or vice versa, then that means that one of these character sequences will be between them, so sed will not see them as adjacent characters.

Community
  • 1
  • 1
ruakh
  • 175,680
  • 26
  • 273
  • 307
0

The character class \s will match the whitespace characters and

For example:

$ sed -e "s/\s\{3,\}/  /g" inputFile

will substitute every sequence of at least 3 whitespaces with two spaces.

Hunter
  • 820
  • 8
  • 19
0
grep --color=always $@ |sed 's/^ //g'

Removes leading white spaces.

Anjan Biswas
  • 7,746
  • 5
  • 47
  • 77