Insert a new line at the beginning of a file

bash, command-line-interface, regex

Solution

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

Problem

Is it any way to find all files like `*.js` and insert some specific line at the beginning of the file? looking for something like: `find . -name '*.js' -exec sh -c '[insert this 'string'] "${0%.js}"' {} \;`

Original source

Related problems