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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With