Question:
batch job. How to add text to all txt files in current directory?
1970-01-01 00:00:00 UTC
batch job. How to add text to all txt files in current directory?
Three answers:
undercoloteal
2007-04-22 21:00:28 UTC
use grep to check if the text is already in the file (use tail first if you only want to look at the end), if grep returns unsuccessful, use echo or cat to add the text to the file
Cat 9
2007-04-22 19:42:00 UTC
To keep it simple, i would suggest to locate the files that already contain the text in a given path, then move them to a temp directory and execute the command you already know on the remaining files (this will avoid having the text appended twice). Final step, return the files from the temp dir to the original dir.
Kevin
2007-04-23 18:18:20 UTC
This just takes one extra step from what you already have. You can search for the string "written by john smith" in all of the text files. If that "find" _fails_, then you can execute the addition of text to the file.



for %f in (*.txt) do find /i "Written by John Smith" "%f" || copy %f+mytext.txt %f /y



The double pipe symbol || (that's the other symbol on the backslash key) basically says "if the command before me fails, then do the command after me".



So, if the "find" command doesn't find your text in a text file, it fails, and the copy command takes place.



NOTE: If you need to do this for all text files throughout your subdirectories, then you need to get a little more advanced on the "for /f" options, like this, (all on one line)



for /f "tokens=*" %f in ('dir *.txt /b /s') do find /i "Written by John Smith" "%f" || copy "%f"+mytext.txt "%f" /y



This will search your entire subdirectory structure for *.txt files and try to find "Written by John Smith" in them. If it doesn't find that text in the file, then it will append your mytext.txt file to them.



Finally, you don't actually need to do a copy command to tag your files. You could just echo your text into the file, like this, (all on one line),



for /f "tokens=*" %f in ('dir *.txt /b /s') do find /i "Written by John Smith" "%f" || echo Written by John Smith>>"%f"


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...