Šimon Tóth
Šimon Tóth

Reputation: 36433

Print only parts that match regex

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?

Upvotes: 24

Views: 36123

Answers (3)

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

Upvotes: 35

swingbit
swingbit

Reputation: 2745

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 

Upvotes: 5

anubhava
anubhava

Reputation: 784918

Its hacky but you can use this for sed only version:

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

OUTPUT:

_c
_e

Upvotes: 1

Related Questions