2

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.

RunLoop
  • 20,288
  • 21
  • 96
  • 151

3 Answers3

5

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 {}" \;
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Thanks, but this does not work. When I replace filetoaddto.txt with *.txt nothing happens. Your second line of code does not even reference texttoadd.txt – RunLoop Apr 13 '14 at 07:35
  • I see what happened, sorry. I have updated it and there shouldn't be any need to change anything now. Please try again. – Mark Setchell Apr 13 '14 at 07:57
1

This works pretty well for me:

$ for fn in `find . -name '*.txt'`; do; cat textToAdd.txt $fn > $$.tmp && mv $$.tmp $fn; done;
Stefano Saitta
  • 1,844
  • 1
  • 19
  • 34
0

Based on this, you can try:

for fn in `ls -R /folderName`; do cat "$fn" >> fileName;  done
Community
  • 1
  • 1
Sparkler
  • 2,581
  • 1
  • 22
  • 41