Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
    
What is the '' for? –  Hauke Laging Feb 25 '13 at 12:01

3 Answers 3

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 http://unix.stackexchange.com/questions/tagged/find

share|improve this answer
1  
Nice edit Stephane, especially appreciated the wiki change notes –  Glenn Feb 26 '13 at 9:19

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"
' -- {} \;
share|improve this answer
    
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 –  sputnick May 27 '13 at 10:26

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
share|improve this answer
    
You actually need to use job/**/*.html (the bash version of globstar is rather limited). –  evilsoup Sep 11 '13 at 20:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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