I'm trying to match replace a multiple lines block with sed and I can't figure it out ..
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'testblah', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
I think the easiest way to do it would be something like this;
s开发者_如何学编程ed -i "s/^DATABASES\s?+=\s?+{$+8/test/" settings.py
In short I want to find the DATABASES = {
include the 8 following lines in the capture and replace that with something else.
Any ideas of what's wrong ?
$ cat > f.sed
/^DATABASES/,/^}/c\
\
A block of replacement\
...text.
$ sed -f f.sed test.txt
Update: In general one should look at SO answers as directions to take rather than finished recipes. As Brian points out, details in the regular expressions will affect how general and how specific the answer is. You may well wish to make any given suggestion more of one or the other w.r.t. any pattern class...
Regular expressions aren't powerful enough to accurately match pairs of braces. You would need a context free grammar for that. Here is the closest to what you're original question was asking that sed can do:
Replace line starting with DATABASES
and 9 following lines with test
sed -n -e '/^DATABASES/i test' -e '/^DATABASES/{n;n;n;n;n;n;n;n;n;n;};p' settings.py
If you're not forced to use sed, grep -A 8 'your regexp' might work. (GNU grep)
This is probably more easily solved in perl than in sed. For one thing, it’s trivial to do multiline matches.
perl -0777 -pe 's/foo.*?bar/glarch/sg'
But for another, you can actually do recursive matching with nested brackets, which I fear you may need here.
Also, since perl uses EREs and sed uses BREs, you will have an easier time at it since you won’t need so many backslashes.
Also, all the \s+
type things are supported.
Also, if this is UTF-8 text, you will still be fine; just add a -CSD
type command-line flag.
Also, there is a sed-to-perl translator called s2p, so you know that it’s a proper superset.
Gosh, that’s sure a lot of also s. ☺
精彩评论