How do I replace part of url string without knowing beforehand what the string would be ? For example below is Ubuntu mirror. I want to set mirror to my liking.
Basically, I want replace (jp, us provided as an example, I think for every country they have their own ubuntu mirrors).
deb http://us.archive.ubuntu.com/ubuntu/ focal multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ focal multiverse
deb http://us.archive.ubuntu.com/ubuntu/ focal-updates multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ focal-updates multiverse
deb http://jp.archive.ubuntu.com/ubuntu/ focal multiverse
# deb-src http://jp.archive.ubuntu.com/ubuntu/ focal multiverse
deb http://jp.archive.ubuntu.com/ubuntu/ focal-updates multiverse
# deb-src http://jp.archive.ubuntu.com/ubuntu/ focal-updates multiverse
deb http://archive.ubuntu.com/ubuntu focal multiverse
# deb-src http://archive.ubuntu.com/ubuntu focal multiverse
deb http://archive.ubuntu.com/ubuntu focal-updates multiverse
# deb-src http://archive.ubuntu.com/ubuntu focal-updates multiverse
To following.
deb http://mirror.sg.gs/ubuntu focal multiverse
# deb-src http://mirror.sg.gs/ubuntu focal multiverse
deb http://mirror.sg.gs/ubuntu focal-updates multiverse
# deb-src http://mirror.sg.gs/ubuntu focal-updates multiverse
deb http://mirror.sg.gs/ubuntu focal multiverse
# deb-src http://mirror.sg.gs/ubuntu focal multiverse
deb http://mirror.sg.gs/ubuntu focal-updates multiverse
# deb-src http://mirror.sg.gs/ubuntu focal-updates multiverse
deb http://mirror.sg.gs/ubuntu focal multiverse
# deb-src http://mirror.sg.gs/ubuntu focal multiverse
deb http://mirror.sg.gs/ubuntu focal-updates multiverse
# deb-src http://mirror.sg.gs/ubuntu focal-updates multiverse
Possibly with sed
, awk
.
3
Answers
An easy solution for perl:
Explanation: This replaces an optional part of (non-space and non-slashes followed by a
.
) beforearchive.ubuntu.com
bymirror.sg.gs
.If you prefer sed:
Explanation: This sed command replaces everything between
http://
orhttps://
, followed by an optional part (of no slashes), ending witharchive.ubuntu.com
with your host.Here are the two examples updating
/etc/apt/sources.list
in-place:I would however replace everything incl. the URL scheme (http/https/ftp). That’s also easier to read:
This solution replaces everything between the "" and the first "" (not including these three ""s), then replaces the first 3 ""s (the "" and the first "") with temporary "~"s, then removes the remaining "/"s, then replaces the three temporary "~"s with ""s:
Using any sed: