Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: extraction of a string from one another



Alternatively, you could use a regex match:

zsh% h=http://www.try.org/examples/easy
zsh% [[ $h =~ ^(https?://[^/]*) ]]
zsh% print $match[1]

http://www.try.org


I don't think there's a solution using builtins that doesn't require two lines of code, though I could be wrong.

You could always use an external program instead of zsh builtins. Here are a couple other regex-based solutions:

zsh% grep -o '^https\?://[^/]*' <<<"$h"
http://www.try.org

zsh% sed -nE 's,^(https?://[^/]*).*$,\1,p' <<<"$h" 
http://www.try.org

And one that does a similar split/join thing as my last message:

zsh% awk -v{,O}FS=/ '{print $1,$2,$3}' <<<"$h" 
http://www.try.org


On Sun, Dec 8, 2024 at 3:46 AM Mark J. Reed <markjreed@xxxxxxxxx> wrote:
Well, there are several ways. For instance, you can split on slashes, then join back just the first three components:

zsh% h=http://www.try.org/examples/easy
zsh% a=("${(@s[/])h}")
zsh% print "${(j[/])a[1,3]}"

http://www.try.org


On Sat, Dec 7, 2024 at 11:17 PM aegy <aegy@xxxxxxx> wrote:
Hi,

h=http://www.try.org/examples/easy

how can I obtain  http://www.try.org from $h ?

thanks,
guido



--
Mark J. Reed <markjreed@xxxxxxxxx>


--
Mark J. Reed <markjreed@xxxxxxxxx>


Messages sorted by: Reverse Date, Date, Thread, Author