vir2al
vir2al

Reputation: 837

Change variable value with regular expression

I have a string: http://user_name:[email protected]/gitproject.git and want to make it without user and pass - http://example.com/gitproject.git

i.e.

http://user_name:[email protected]/gitproject.git 

to

http://example.com/gitproject.git

How can I do it automatically in bash?

Upvotes: 0

Views: 102

Answers (4)

iruvar
iruvar

Reputation: 23374

A pure bash possibility

var='http://user_name:[email protected]/gitproject.git'
pat='(http://).*?@(.*)'
[[ $var =~ $pat ]]
echo "${BASH_REMATCH[1]}${BASH_REMATCH[2]}"
http://example.com/gitproject.git

Upvotes: 1

anubhava
anubhava

Reputation: 784958

This sed should work:

s="http://user_name:[email protected]/gitproject.git"
sed 's~^\(.*//\)[^@]*@\(.*\)$~\1\2~' <<< "$s"

http://example.com/gitproject.git

Using pure BASH

echo "${s/*@/http://}"

http://example.com/gitproject.git

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191729

Some languages you may have installed such as php or python have excellent URL parsing facilities. For example, php:

$url = parse_url("http://user_name:[email protected]/gitproject.git "); 
return "$url[scheme]://" . $url['host'] . $url['path'];

However, since that's not what you asked for, you can still do it in sed:

sed -r "s#(.*?://).*?@(.*)#\1\2#" <<<"http://user:[email protected]/git"

Upvotes: 2

fedorqui
fedorqui

Reputation: 289505

With sed:

$ sed "s#//.*@#//#g" <<< "http://user_name:[email protected]/gitproject.git"
http://example.com/gitproject.git

Upvotes: 1

Related Questions