No output from sed when grouping with multiple parentheses

Viewed 50

I have this sed expression to replace the output with the actual match of the regex expression:

$( sed -n 's/.*\((http|https):\/\/[a-zA-Z0-9_-]*(\.[a-zA-Z0-9_-]*)*\).*/\1/pg' < access-medium.log )

Input:

66.249.76.98 - - [12/Aug/2016:06:26:33 +0200] "GET /kod-exempel/dynamic_php_menu/ HTTP/1.1" 301 3859 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"

Desired output:

http://www.google.com or https://www.google.com

I use *\ before and after expression to replace with nothing and then I print the line, what am I missing here?

1 Answers

You are using a POSIX BRE pattern (no -E nor -r used), so you need to remember that capturing parentheses and alternation operator (with GNU sed in mind) must be escaped.

You can use

sed -n 's~.*\(https\{0,1\}://[^/]*\).*~\1~p'

See the online sed demo

Details

  • -n - option suppressing default line output
  • .*\(https\{0,1\}://[^)]*\).* - regex pattern matching
    • .* - any zero or more chars
    • \(https\{0,1\}://[^/]*\) - Group 1: http, and optional s, ://, then zero or more chars other than /
    • .* - any zero or more chars
  • \1 - replacement is the Group 1 value
  • p - prints the result of the substitution.
Related