Add contents of 1 file to the top of another file
-
21-12-2019 - |
Question
I need to insert text from 1 file at the top of a large number of files in a directory and its subdirectories. I have been able to do this successfully on a file by file basis using ed:
ed -s FileToAddTo.txt <<< $'0r TextToAdd.txt\nw'
However, when I replace FileToAddTo.txt with *.txt, nothing happens. How can I modify this, or use another Unix command such as sed, to add the contents of TextToAdd.txt recursively to all files in a directory ending with a specific extension? e.g
ed -rs *.txt <<< $'0r TextToAdd.txt\nw'
Please note that the code above this line does not work, it merely demonstrates what I would like to achieve.
Solution
Like this:
cat TextToAdd.txt FileToAddTo.txt > $$.tmp && mv $$.tmp FileToAddTo.txt
i.e. cat the new header file and the original file into a temporary file and then, if it was successful, rename the temporary file as the original.
And to run recursively !! PLEASE TEST ON BACKED UP DATA!!!
find . -type f -name "*.txt" -exec sh -c "cat TextToAdd.txt {} > $$.tmp && mv $$.tmp {}" \;
OTHER TIPS
This works pretty well for me:
$ for fn in `find . -name '*.txt'`; do; cat textToAdd.txt $fn > $$.tmp && mv $$.tmp $fn; done;
Based on this, you can try:
for fn in `ls -R /folderName`; do cat "$fn" >> fileName; done