views:

535

answers:

3

Hi, I've made several attempts at this but get nothing but "can't open..." errors, so I'm asking here:

I want to find all instances of the string "SOME TEXT" within a directory full of HTML files. Then the search results should be output to a file in that same directory (D:\myfiles)

+1  A: 

Here's a sample batch file that'll do the trick.

@echo off
setlocal
pushd D:\myfiles

rem case-insensitive search for the string "SOME TEXT" in all html files
rem in the current directory, piping the output to the results.txt file
rem in teh same directory
findstr /ip /c:"SOME TEXT" *.html > results.txt

popd
endlocal

Update: Some caveats to using findstr command.

If your string contains angle brackets, you have to escape them using the CMD escape character - ^. So, if you want to search for <TITLE>, you have to specify it as /c:"^<TITLE^>".

If you want only file names, change /ip to /im. Also, you can add /s to search subfolders. In general, you can play with the different findstr options as listed in findstr /?.

Findstr will find the text only in UTF-8 encoded files. If the HTML files are UTF-16 encoded (ie, each character takes two bytes), findstr will not find the text.

I would also suggest running the command without the piping to the results.txt first to get the right findstr options and make sure it outputs what you need.

Franci Penov
Wow, thanks for the quick answer - Using the code shown below created a results file. However it did not seem to be outputting filenames, but the actual code that contained the string. @echo offsetlocalpushd d:\Sitesfindstr /ip /c:"THE" *.htm > results.txtpopdendlocalBut, it only worked once! When "THE" was changed to the real string: "<TITLE>OUR COURSES:</TITLE>"it stopped working. No more results file, no error, nothing. Thinking the brackets might be the problem, I changed it to "OUR COURSES:" but no luck. Even when changed back to "THE" it doesn't work!Thanks
Ellen
A: 
for %%f in (*.html) do findstr /i /m /p /c:"SOME TEXT" "%%f" >> results.txt
A: 

Thanks to both of you for your suggestions - I'll get back to this on Monday!