Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print only parts that match regex

Tags:

echo "a b _c d _e f" | sed 's/[ ]*_[a-z]\+//g'

The result will be a b d f.

Now, how can I turn it around, and only print _c _e, while assuming nothing about the rest of the line?

like image 371
Šimon Tóth Avatar asked Mar 07 '12 12:03

Šimon Tóth


2 Answers

If the question is "How can I print only substrings that match specific a regular expression using sed?" then it will be really hard to achieve (and not an obvious solution).

grep could be more helpful in that case. The -o option prints each matching part on a separate line, -P enables PCRE regex syntax:

$> echo "a b _c d _e f" | grep -o -P "(\ *_[a-z]+)"  _c  _e 

And finally

$> echo `echo "a b _c d _e f" | grep -o -P "(\ *_[a-z]+)"` _c _e 
like image 108
ДМИТРИЙ МАЛИКОВ Avatar answered Nov 30 '22 05:11

ДМИТРИЙ МАЛИКОВ


Identify the patterns you want, surrounded by the patterns you don't want, and emit only those:

echo "a b _c d _e f" | sed 's/[^_]*\s*\(_[a-z]\)[^_]*/\1 /g' 

OUTPUT:

_c _e  
like image 38
cornuz Avatar answered Nov 30 '22 04:11

cornuz