2

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/
2
  • 1
    is this not what you expected? Commented Dec 17, 2013 at 20:21
  • @UriMikhli the second part is what I expected but it wasn't working anubhava pointed out that I was using single quotes which wasn't expanding the shell variable when sed was ran. Commented Dec 17, 2013 at 20:23

3 Answers 3

4

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

sed "/$mirrorRegex/s/# //"
Sign up to request clarification or add additional context in comments.

1 Comment

Wow I don't know why I didn't remember that. Thank you, don't I feel foolish. I'll accept this as the answer as soon as I can.
1

You can use awk like this to do the same:

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

1 Comment

Awesome thanks for showing me that. I figured awk would work as well I'm trying to learn sed and awk.
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.