Mark
Mark

Reputation: 8678

Print text between delimiters using sed

Suppose I have op(abc)asdfasdf and I need sed to print abc between the brackets. What would work for me? (Note: I only want the text between first pair of delimiters on a line, and nothing if a particular line of input does not have a pair of brackets.)

Upvotes: 3

Views: 5864

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

sed -n -e '/^[^(]*(\([^)]*\)).*/s//\1/p'

The pattern looks for lines that start with a list of zero or more characters that are not open parentheses, then an open parenthesis; then start remembering a list of zero or more characters that are not close parentheses, then a close parenthesis, followed by anything. Replace the input with the list you remembered and print it. The -n means 'do not print by default' - any lines of input without the parentheses will not be printed.

Upvotes: 4

Slava Semushin
Slava Semushin

Reputation: 15204

$ echo 'op(abc)asdfasdf' | sed 's|[^(]*(\([^)]*\)).*|\1|'
abc

Upvotes: 5

Related Questions