SED question
Hello - I've never posted a real question here before so if this is in the wrong section I apologize. However here's my question:
I want to write a one-liner that goes through a file, finds a search string, replaces with something else and then writes the file. I though sed would be the tool I needed? I want to search for relayhost = [something and comment that out - here's one of my attempts: sed 's/relayhost = [smtprelay/#relayhost = [smtprelay/g' <test.txt >test.out and then I get this: sed: -e expression #1, char 50: unterminated `s' command Would someone please help me format this? I've a couple hundred servers I need to make this change on and would rather not manually edit them. :) Additionally I have to find another line that is commented out and uncomment it. Thanks for your help in advance! |
Hope this will work
Quote:
|
szboardstretcher's solution looks OK - basically you need to escape the regex special characters. But I think only [ matters. Plus you can use avoid some typing with a capture group:
Code:
sed 's/\(relayhost = \[smtprelay\)/#\1/g' test.txt > test.out |
Both worked!
Sorry I took so long to get back to you - I just switched from days to mid shift.
Thank you both - I tested each string individually and they both worked equally well, although SecretCode's way baffled me a bit - I don't understand the group concept but will research. Thanks again! |
Groups in regular expressions are very useful. If you surround a section in the left hand side with parentheses ( ) then when you put \1 in the right hand side it gets replaced with whatever was matched in that section of the left hand side.
Say you wanted to comment out any line that had "= [" in it, not just that text, you can't retype the text on the rhs because you don't know what it is: Code:
sed 's/\(.* = \[.*\)/#\1/g' |
I'm not sure how universal that construct is....In sed, it's called a "backreference" and it's mostly used in the "s" command.
To avoid the need to "escape" the ( ), use sed -r |
Not tested (I'm on lunch at work):
Code:
sed '/relayhost = \[smtprelay/s//#&/' file Code:
sed '/relayhost = \[smtprelay/s/^/#/' file Code:
sed '/^relayhost/s/^/#/' file |
Quote:
Regex Tutorial - Named Capturing Groups - Backreference Names: Quote:
In perl, the backreferences are \g1 etc (not \1) and there are "matching variables" $1 etc. Quote:
|
All times are GMT -5. The time now is 05:55 AM. |