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.)
Asked
Active
Viewed 5,792 times
3

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278

Mark
- 8,408
- 15
- 57
- 81
-
The duplicate https://stackoverflow.com/questions/23875129/extract-text-between-two-given-different-delimiters-in-a-given-text-in-bash has a number of non-`sed` solutions. – tripleee Feb 09 '21 at 08:30
2 Answers
5
$ echo 'op(abc)asdfasdf' | sed 's|[^(]*(\([^)]*\)).*|\1|'
abc

Slava Semushin
- 14,904
- 7
- 53
- 69
-
awesome it works, could you please explain what the syntax mean so I can play around with it to solve similar problems? – Mark May 12 '11 at 02:21
-
@mark see answer from @jonathan-leffler above where he fully describe how it works. One difference is that I not use -n option (but probably should because when string not match, my one-liner will print original string). – Slava Semushin May 12 '11 at 02:28
-
@Mark: the explanation is essentially the same as in my answer; the solution is essentially the same as mine. One difference is that php-coder uses '|' where I use '/'. Otherwise, his solution prints lines that don't contain a matched pair of parentheses, whereas mine deletes lines that don't match - a difference of interpretation of your question. On the sample input, both solutions produce the same output. – Jonathan Leffler May 12 '11 at 02:30
4
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.

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278