Insert a new line at the beginning of a file
Here's a way to add a line to the beginning of a file:
sed -i '1s/^/line_to_be_added\n/' file
Then, you could use the code above with find
to achieve your ultimate goal:
find . -type f -name '*.js' -exec sed -i '1s/^/line_to_be_added\n/' {} \;
Note: this answer was tested and works with GNU
sed
.
Edit: the code above would not work properly on a .js
file that is empty, as the sed
command above does not work as expected on empty files. A workaround to that would be to test if the file is empty, and if it is, add the desired line via echo
, otherwise add the desired line via sed
. This all can be done in a (long) one-liner, as follows:
find . -type f -name '*.js' -exec bash -c 'if [ ! -s "{}" ]; then echo "line_to_be_added" >> {}; else sed -i "1s/^/line_to_be_added\n/" {}; fi' \;
Edit 2: As user Sarkis Arutiunian pointed out, we need to add ''
before the expression and \'$'
before \n
to make this work properly in MacOS sed. Here an example
sed -i '' '1s/^/line_to_be_added\'$'\n/' filename.js
Edit 3: This also works, and editors will know how to syntax highlight it:
sed -i '' $'1s/^/line_to_be_added\\\n/' filename.js
Portability: Use Sed's Hold Space
If you want a solution that works portably with both GNU and BSD sed, use the following to prepend text to the first line, and then pass the rest through unchanged:
sed '1 { x; s/^.*/foo/; G; }' example.txt
Assuming a corpus of:
bar
baz
this will print:
foo bar baz
You can save the transformation in a script, and then use find or xargs and the sed -i
flag for in-place edits once you're sure everything is working the way you expect.
Caveat
Using sed has one major limitation: if the file is empty, it won't work as you might expect. That's not something that seems likely from your original question, but if that's a possibility then you need to use something like cat <(echo foo) example.txt | sponge example.txt
to edit the file in-place, or use temporary files and move them after concatenating them.
NB: Sponge is non-standard. It can be found in the moreutils package.