linuxbashshell

How to get `grep` to emit the right side of 'URL=http://example.com'?


So I'm trying to grep the following file myfile.txt:

[Section]
URL=http://example.com

I want it to return everything after the URL=, so only http://example.com.

If I try any of the following, they do not work:

>grep -m1 -i 'url=' myfile.txt
URL=http://example.com
>grep -m1 -i 'http.+*' myfile.txt
URL=http://example.com
>grep -m1 -i -o 'http\.$' myfile.txt

>grep -m1 -i -o 'http\.*' myfile.txt
http
>grep -m1 -i -o 'http\.*$' 
>

How can grep emit everything to the right of the equals symbol? It seems to refuse to match to the end of the line. And this will fail if the address happens to be anything other than 'http' (such as FTP, etc.)


Additions:


Solution

  • Instead of grep, have you considered sed?

    Given your sample input file, this command...

    sed -n '/^URL=/ s/.*=//p' myfile.txt
    

    Produces as output:

    http://example.com
    

    Or maybe awk:

    awk -F= '/^URL=/ {print $2}' myfile.txt
    

    The problem with grep in this instance is that it's primarily a tool for returning matched lines; it's not really meant for performing transformations on those matches.

    The -o option is an interesting idea, but there's not really anyway to restrict it to match only the part after the = unless you prefilter the input like this:

    grep '^URL=' myfile.txt | grep -o '[^=]*$'