krizzo
krizzo

Reputation: 1883

Uncommenting a config line based on regex with string replace

I have a config file with a bunch of URLs for repos that are commented out. I need to uncomment a specific one and thought sed would make it easy to match a regex then doing a string replace on that line.

I was wondering if my regex in correct for sed syntax or if the sed command is not correct?

mirrorRegex="^# http.*vendor.*distroARCH-1.1\/"
sed '/$mirrorRegex/s/# //' /etc/repos

Before:

# ftp://mirrors.example.com/distro/distroARCH-1.1/
# http://mirrors.example.com/distro/distroARCH-1.1/
# ftp://packages.vendor.org/distro/distro/distroARCH-1.1/
# http://packages.vendor.org/distro/distro/distroARCH-1.1/
# http://mirror.school.edu/pub/distro/distroARCH-1.1/
# http://system.site3.com/distroARCH-1.1/

After: What is expected.

# ftp://mirrors.example.com/distro/distroARCH-1.1/
# http://mirrors.example.com/distro/distroARCH-1.1/
# ftp://packages.vendor.org/distro/distro/distroARCH-1.1/
http://packages.vendor.org/distro/distro/distroARCH-1.1/
# http://mirror.school.edu/pub/distro/distroARCH-1.1/
# http://system.site3.com/distroARCH-1.1/

Upvotes: 2

Views: 423

Answers (3)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's|^#[[:blank:]]*\(http.*vendor.*distroARCH-1.1/.*\)|\1|' YourFile

use of other separator than default / (| in this case) will help

and with variable version

Content='http.*vendor.*distroARCH-1.1/'
sed "s|^#[[:blank:]]*\(${Content}.*\)|\1|" YourFile

Upvotes: 0

Jotne
Jotne

Reputation: 41446

You can use awk like this to do the same:

awk '$0~var {sub(/^# /,x)}1' var="$mirrorRegex" file

Upvotes: 1

anubhava
anubhava

Reputation: 784958

You need to use double quotes in order to expand shell variables:

sed "/$mirrorRegex/s/# //"

Upvotes: 4

Related Questions