red888
red888

Reputation: 31672

sed not working as expected (trying to get value between two matches in a string)

I have a file (/tmp/test) the has a the string "aaabbbccc" in it

I want to extract "bbb" from the string with sed.

Doing this returns the entire string:

sed -n '/aaa/,/ccc/p' /tmp/test

I just want to return bbb from the string with sed (I am trying to learn sed so not interested in other solutions for this)

Upvotes: 1

Views: 37

Answers (2)

Cyrus
Cyrus

Reputation: 88959

With GNU sed:

sed 's/aaa\(.*\)ccc/\1/' /tmp/test

Output:

bbb

See: The Stack Overflow Regular Expressions FAQ

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47137

Sed works on a line basic, and a,b{action} will run action for lines matching a until lines matching b. In your case

sed -n '/aaa/,/ccc/p'

will start printing lines when /aaa/ is matched, and stop when /ccc/ is matched which is not what you want.

To manipulate a line there is multiply options, one is s/search/replace/ which can be utilized to remove the leading aaa and trailing ccc:

% sed 's/^aaa\|ccc$//g' /tmp/test
bbb

Breakdown:

s/
  ^aaa  # Match literal aaa in beginning of string
  \|    # ... or ...
  ccc$  # Match literal ccc at the end of the sting
//      # Replace with nothing
g       # Global (Do until there is no more matches, normally when a match is
        # found and replacement is made this command stops replacing) 

If you are not sure how many a's and c's you have you can use:

% sed 's/^aa*\|cc*$//g' /tmp/test
bbb

Which will match literal a followed by zero or more a's at the beginning of the line. Same for the c's but just at the end.

Upvotes: 3

Related Questions