4

So I recently upgraded Django from 1.4 to 1.5. I found out I need to update all my template codes to add single quotes like from

{% url user_detail pk=user.pk %}

to

{% url 'user_detail' pk=user.pk %}

I'm kind of new to bash commands like sed, but I approached my issue in 2 parts.

The 1st part was to get a list of all the files that needs updating. I did that with

ack "{% url" | cut -d ":" -f1 | uniq

this will give me an ouput like

templates/some_file.html
templates/admin/another_file.html

The 2nd part was playing around with sed

cat templates/some_file.html | sed "s/{% url \([A-Za-z0-9_]*\) /{% url '\1' /g"

Both of those commands work fine. Now the question is

how do I combine those two commands so that sed will add single-quotes around the url name in every file found by ack?

If I try

ack "{% url" | cut -d ":" -f1 | uniq | sed -i "s/{% url \([A-Za-z0-9_]*\) /{% url '\1' /g"

it gives me the error

sed: -i may not be used with stdin

EDIT

I'm running OS X (BSD variant) so I needed to use sed -i "" "s/{% url \([A-Za-z0-9_]*\) /{% url '\1' /g".

hobbes3
  • 28,078
  • 24
  • 87
  • 116

1 Answers1

4
ack -l "{% url" | xargs sed -i "s/{% url \([A-Za-z0-9_]*\) /{% url '\1' /g"

-l lists matching files from ack (a simpler version of your cut/uniq). xargs performs the operation on each argument acquired from the pipe (i.e. each file). What you were trying to do would be sed on the actual string of the list of files from stdin which of course can't be updated in place.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • I ran that command and when I did `ack` again I noticed that none of the files changed. Well I did get one error: `sed: 1: "doors/templatetags/brea ...": extra characters at the end of d command` but I think that's just my `sed` expression not catching all the cases. – hobbes3 Apr 11 '13 at 05:19
  • @hobbes3 it's weird that none of the files changed -- I did a very minimal test. Try `sed` without `-i` first to see if you get any output – Explosion Pills Apr 11 '13 at 05:20
  • ok I ran `ack -l "{% url" | xargs sed "s/{% url \([A-Za-z0-9_.]*\) /{% url '\1' /g" | grep '{% url'` (I forgot to find `.` inside the regex) and it shows the output wth the added single-quote. – hobbes3 Apr 11 '13 at 05:24
  • Is it because that one error `sed: 1: ... extra characters at the end of the d command` is aborting the whole `sed` rewrite of the files? – hobbes3 Apr 11 '13 at 05:27
  • This question (http://stackoverflow.com/questions/7648328/getting-sed-error) helped. I changed the command to `sed -i "" "s/{% url ...` and it worked! I failed to mention my system is OS X, which is a BSD variant. Thanks. – hobbes3 Apr 11 '13 at 13:33
  • @hobbes3 ah, I see. I'm on a Linux machine – Explosion Pills Apr 11 '13 at 13:37