I try to grep and it tries to work with the special characters.
With basic regular expressions (BRE) enabled (the default in absence of the switches -E
, -F
or -P
), grep interprets the plus character as a literal +
.
The problem is that only lines that begin with [ + ]
or [ - ]
get sent to STDOUT, while lines that begin with [ ? ]
get sent to STDERR. Only STDOUT gets piped to grep; STDERR gets printed directly on the terminal.
To obtain the output you're expecting, execute the following command:
service --status-all 2>&1 | grep '+'
2>&1
sends STDERR to STDOUT, so grep is able to filter it.
Since you're printing only lines begnning with [ + ]
, you might as well filter that part out. To do so, you can use the -o
switch to print only matched output, the -P
switch to enable Perl Compatible Regular Expressions (PCRE) and a look-behind assertion ((?<=...)
):
service --status-all 2>&1 | grep -Po '(?<= \[\ \+ \] ).*'
Note that with PCRE, you have to escape the plus sign and the brackets with a backslash.
The same result can be achieved with BRE, without look-behinds and without knowing the exact number of spaces if you use sed:
service --status-all 2>&1 | grep '+' | sed 's/.*] *//'
Here, the BRE .*] *
(everything up to the right bracket, followed by any number of spaces) gets replaced by the empty string.
try with
sudo service --status-all | grep -L '+'
because the'
already says that it won't be escape character... – poz2k4444 – 2013-01-17T02:02:13.653