Skip to content

Instantly share code, notes, and snippets.

@mfrost503
Last active August 29, 2015 14:25
Show Gist options
  • Save mfrost503/ca5d88f6570552f5d2a1 to your computer and use it in GitHub Desktop.
Save mfrost503/ca5d88f6570552f5d2a1 to your computer and use it in GitHub Desktop.
Adding the same content to any number of files
find ./ -maxdepth 2 -type f -name '*.php' -print 0 | xargs -0 grep -L \/path\/to\/some\/file | xargs sed -i "3i require\_once \'..\/path\/to\/some\/file"
So what is this doing:
find ./ - find files in the current directory
- maxdepth 2: look at all the files in the current directory and any files 2 directory levels deep
- type f: looking for files
- name '*.php': any file with a .php extension
- print0: since we're piping to grep, we have to output the file list the way grep expects to receive it
|
xargs -0: take the list of files and output them in a single line (-0 - which is how grep wants them)
grep -L: List any files that DON'T have a line that matches the pattern
<pattern>: the matter you are trying to match/not match
|
sed -i: edit these files in line
"
3i: insert text on the 3rd line of file
"<text to enter>": the text you want to add on the third line.
In this case we're taking all the php files 2 levels deep that don't already have our fictional include/require in them and then we are adding them at line 3. It can be a bit scary if you don't know what you are doing, so make sure you don't do it live and make sure you you can remedy anything that you mess up. You'll also have to escape any characters like: []'"/_() etc
I always do this on a single file that I can do a 'git checkout file' on to make sure I have the pattern, escaping, etc correct before trying to do it on a large batch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment