Insert a new line at the beginning of the file

Is it possible to find all files of a type *.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}"' {} \;

+6


source to share


2 answers


Here's a way to add a line to the beginning of the file:

sed -i '1s/^/line_to_be_added\n/' file

      

Then you can use the above code with find

to achieve your ultimate goal:

find . -type f -name '*.js' -exec sed -i '1s/^/line_to_be_added\n/' {} \;

      

Note : This answer has been tested and works with GNU

sed

.

Edit : The above code will not work as expected for an empty file .js

as the above command sed

does not work as expected for empty files. A workaround might be to check if the file is empty, and if so, add the desired line with echo

, otherwise add the desired line with sed

. This can all be done in a (long) one-line, like this:



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 pointed out by user Sarkis Arutiunian, we need to add ''

before the expression and \'$'

before in \n

order for sed to work properly on macOS. Here's an example

sed -i '' '1s/^/line_to_be_added\'$'\n/' filename.js

      

Edit 3 : This works as well, and editors will know how to syntax highlight it:

sed -i '' $'1s/^/line_to_be_added\\\n/' filename.js

      

+6


source


Portability: Using Sed Waitspace

If you want a solution that works with both GNU and BSD, use the following to add text on the first line and then pass the rest unchanged:

sed '1 { x; s/^.*/foo/; G; }' example.txt

      

Assuming a case:

bar
baz

      

this will print:



foo
bar
baz

      

You can save the conversion to a script and then use find or xargs and the sed flag -i

to edit in place once you are sure everything is working as you expect.

Caveat

Using sed has one major limitation: if the file is empty, it won't work as you might expect. This is not what seems likely from your original question, but if possible, 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: Non-standard sponge. It can be found in the moreutils package .

+2


source







All Articles