I need to amended the following text in a few hundred documents ...
{% url project.app.views.chart %}
so it reads
{% url "project.app.views.chart" %}
Do you know the next way to do this based on the text between the quotes being different each time ?
Thanks,
This works as soons as you don't have any %
char in your input strings:
sed -r 's/url ([^%]+) %/url "\1" %/g'
Test
$ echo '{% url test %}{% url test 2 %}' | sed -r 's/url ([^%]+) %/url "\1" %/g'
{% url "test" %}{% url "test 2" %}
Let's explain this answer. The -r
option is here because extended regexes
are the one I prefer to use.
Now, the substitution part.
sed 's/pattern/replacement/g'
Is used to replace text, matching pattern as a regular expression
and replacing it by replacement .
The g
is a substitution option that means you want to replace the pattern as many times as it is present in the text.
So here the pattern is url ([^%]+) %
. url
and %
part are pretty logical and easy to get (if not, tell me). The ([^%]+)
means "capture everything that isn't a %
and that is composed by at least a character" . The parenthesis allow to save this part, to reuse it after with \\x
where x is the number of the parenthesis group (Here it will be \\1
).
So when it receives {% url test %}
, the pattern matches url test %
where test
is saved under \\1
, and it rewrites it with url "\\1" %
so url "test" %
. The parts before and after the pattern aren't modified, so it will output {% url "test" %}
To avoid adding another set of quotes if there are already there, just add [^"]
after url
that way : url [^"]
.
Here is the full command :
sed -r 's/url ([^"][^%]+) %/url "\1" %/g'
Assuming you want to wrap string between url
and %}
.
Something like this may work:
sed -e 's/url /url "/' -e 's/ %}/" %}/'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.