1

I was trying with regular expressions to add single quotes to a word, taking care if in the expression I have single, doubles or none quotes. I have this

find . -type f -print0 | xargs -0 sed -i "s/{% url \([^\' >][^\" >][^ >]*\)/{% url \'\1\'/g"

Example

{% url something foo bar %}
{% url "something" foo bar %}
{% url 'something' foo bar %}

should be replaced by

{% url 'something' foo bar %}

But in case

{% url "something.else" foo bar %}

it changes to

{% url '"something.else"' foo bar %}

Single quotes can't be escaped in single qoutes, and the same with doubles/doubles isn't it? How do I do? Regular expressions are fantastic but dificults too. Thanks!!

The origin was problems with urls in Django 1.5

"Django release 1.5: 'url' requires a non-empty first argument. The syntax changed in Django 1.5"

I found an answer to change to double quotes here.

But same problem occurs with single quotes, replace 'word' to "'word'".

Community
  • 1
  • 1
Rulolp
  • 21
  • 5
  • To get good attention to your question, consider formatting your post properly. – slayedbylucifer Mar 07 '14 at 04:48
  • Sorry, I thought It was clearly explained and formatted. I don't understand you what's formatting properly, It's my first question here but a site of reference always, also speak Spanish so I take the opportunity to apologize if there are spelling mistakes too ;) – Rulolp Mar 11 '14 at 04:09

1 Answers1

1

The following might work for you:

sed -r "s/{% url ['\"]?([^ '\"]*)['\"]?/{% url '\1'/g"

For the input:

{% url something foo bar %}
{% url "something" foo bar %}
{% url 'something' foo bar %}
{% url "something.else" foo bar %}

it'd produce:

{% url 'something' foo bar %}
{% url 'something' foo bar %}
{% url 'something' foo bar %}
{% url 'something.else' foo bar %}
devnull
  • 118,548
  • 33
  • 236
  • 227
  • +1 for the simple efficient code. Just a small info that this does not allow a simple quote inside 2 double quote (or the inverse) like `"don't work"`. Solve with 3 s// consecutive, one by case or complete with the `foo bar %}` "pattern". – NeronLeVelu Mar 07 '14 at 07:13
  • 1
    Thanks, but it doesn't work to me. Sed command looks very powerful but too hard. It give me invalid reference whith -i and invalid expression with -r. Also I want to look all files in a directory and change lines so I need find . -type f -print0 | xargs -0 sed -i I understand Seems still continue the same problem whith escaping the single quotes. Solve it using the command I posted, because haven't double quotes, but in the future I need to use it again, luckily there are single or double quotes, but not a mixture of both. Clearly I still do not understand how the regular expression works well – Rulolp Mar 11 '14 at 03:50