0

I am trying to iterate through a list of html files, check to see if {% load static from staticfiles %} exists in the file and if it does not exists, prepend {% load static from staticfiles %} to it.

This is what I have now on 1 file called job/home.html (for testing purposes before applying it to all files):

grep -q '{% load static from staticfiles %}' job/home.html || sed -i '' 's+{% load static from staticfiles %}\n+' job/home.html

So 2 things,

  • How can I make this command recursive for all the html files
  • The line break, \n doesn't seem to be line breaking
1

Try the following, which should return a recursive result

find /home/user/myfolder -name '*.html' -exec sh -c '
  for file do
    yourcommands with "$file"
  done' sh {} +

More about find and lots of examples on http://en.wikipedia.org/wiki/Find and also a few different things in https://unix.stackexchange.com/questions/tagged/find

  • 1
    Nice edit Stephane, especially appreciated the wiki change notes – Glenn Feb 26 '13 at 9:19
0

Try doing this :

find /home/user/myfolder -name '*.html' -exec sh -c '
    fgrep &>/dev/null "{% load static from staticfiles %}" "$1" ||
        sed -i '1i {% load static from staticfiles %}!' "$1"
' -- {} \;
  • I'm getting find: home.html: unknown option – super9 Feb 25 '13 at 16:05
  • You need to quote your glob expansion. – Chris Down May 27 '13 at 9:36
  • Post edited accordingly – Gilles Quenot May 27 '13 at 10:26
0

If you have bash 4 or newer you can use shopt -s globstar to enable recursive globs (among other things):

... job/**/*.html

(thanks @evilsoup!)

This glob will resolve to all .html files anywhere inside job/ (don't be mislead by the second slash; it looks like the glob is actually **/).

To add text to the beginning of a file semi-safely:

echo "text" | cat - yourfile > /tmp/out && mv /tmp/out yourfile

A safer solution would be to use a random temp directory, to avoid almost any other processes interfering with this one:

dir="$(mktemp -d)" && echo "text" | cat - yourfile > "$dir/out" && mv "$dir/out" yourfile
  • You actually need to use job/**/*.html (the bash version of globstar is rather limited). – evilsoup Sep 11 '13 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.