Issue
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
.
Solution
An easy solution for perl:
perl -pe 's/([^\s\/]+\.)?archive\.ubuntu\.com/mirror.sg.gs/g'
Explanation: This replaces an optional part of (non-space and non-slashes followed by a .
) before archive.ubuntu.com
by mirror.sg.gs
.
If you prefer sed:
sed -E 's#(https?://)[^/]*archive.ubuntu.com#\1mirror.sg.gs#'
Explanation: This sed command replaces everything between http://
or https://
, followed by an optional part (of no slashes), ending with archive.ubuntu.com
with your host.
Here are the two examples updating /etc/apt/sources.list
in-place:
perl -i -pe 's/([^\s\/]+\.)?archive\.ubuntu\.com/mirror.sg.gs/g' /etc/apt/sources.list
sed -Ei 's#(https?://)[^/]*archive.ubuntu.com#\1mirror.sg.gs#' /etc/apt/sources.list
I would however replace everything incl. the URL scheme (http/https/ftp). That's also easier to read:
perl -pe 's/\s.*archive\.ubuntu\.com/ http:\/\/mirror.sg.gs/g'
Answered By - steffen Answer Checked By - Mary Flores (WPSolving Volunteer)