BSD (including Mac OS X) version of sed
is not GNU's one, including a subtle difference with in-place remplacements.
On BSD systems, you HAVE TO replace occurrence of sed -i -e
with sed -i '' -e
to make it work.
find -name '*.js'|grep -v '^./node_modules'|while read f;do if (head -n3 "$f"|grep -Fv 'use strict'>/dev/null);then echo "$f";sed -i -e '1i "use strict"\n' "$f";fi;done |
alias rigid="find -name '*.js'|grep -v '^./node_modules'|while read f;do if (head -n3 \"\$f\"|grep -Fv 'use strict'>/dev/null);then echo \"\$f\";sed -i -e '1i \"use strict\";\\n' \"\$f\";fi;done" |
find -name '*.js' `# Find all .js files in current directory, recursively` | \ | |
grep -v '^./node_modules' `# Exclude node_modules folder, you may want to add additional folders here` | \ | |
while read f; do | |
if (head -n3 "$f" | grep -Fv 'use strict' > /dev/null); then `# Check first three lines, thought about shebang` | |
echo "$f" | |
sed -i '1i "use strict"\n' "$f" `# Prepend "use strict", that may break your executable scripts` | |
fi | |
done |
BSD (including Mac OS X) version of sed
is not GNU's one, including a subtle difference with in-place remplacements.
On BSD systems, you HAVE TO replace occurrence of sed -i -e
with sed -i '' -e
to make it work.
@rex, you are my hero :) Your final command has server me quite a bit.
Set it to use -n8
, for our use case. (Comments come before use strict, though I guess it makes sense to see 'use strict' as the first line) Worked perfectly!
I needed to check a huge codebase for
use strict;
at the top of every file and I was dreading it. I thought to myself "Surely nobody has expended the energy to solve this problem already."Then I got here.
You are my hero. Seriously just saved me at least an hour or more trying to get something working together. So thank you.
For future wanderers, though, I did need to modify this slightly for use on a Mac.
brew install gnu-sed
- Seriously, just do it. Makes life so, so much easier.find -name '*.js'
command does not work on a Mac out of the box. You must specify a path as the first argument or the Mac chokes on it. I solved this problem like so:find . -name '*.js'
grep
command to work on the Mac. Instead of inverting with the-v
flag (which wasn't exiting with an error) I flipped it.sed
withgsed
since I installed thegnu-sed
package from brew.The final command that worked for me (whitespace added for clarity) is as follows: