Nithya
Nithya

Reputation: 47

Findstr not returning expected result

Hi all I have the following line of code to list all the files that matches the word Hello

findstr /s "Hello" .\*.* > C:\MyDir\result.txt

I am having multiples files inside my folder as file1.xml and file2.xml but when I execute this script it is giving me only file1.xml but not the file2.xml can some one help me. Content inside my both files is <Hello></Hello> and <Hello>

enter image description here

enter image description here

enter image description here

Upvotes: 0

Views: 3871

Answers (2)

DavidH
DavidH

Reputation: 56

I think that you might want to check your syntax. You are calling a Write redirect > when I think you mean to use the append redirect >>. So, your batch file is doing its job... It's just continually overwriting the previous result.

Try this:

findstr /s "Hello" .\*.* >> C:\MyDir\result.txt

For more information about redirects, see this page on https://ss64.com/nt/syntax-redirection.html ss64.com

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

Assuming that your casing is correct and you want case-sensitive matching (use /i to make matches case-insensitive) I would suspect that your second file is Unicode-encoded. You can verify that by opening the file in Notepad and clicking File → SaveAs.... The Encoding dropdown at the bottom of the SaveAs dialog shows the current encoding of the file.

findstr can't handle Unicode files, but find can (Raymond Chen explained why there are two commands). However, find can't recurse into subfolders, so you'd need either a for loop

for /r %f in (*.*) do find "Hello" "%~ff"

or forfiles:

forfiles /s /c "cmd /c find \"Hello\" @path"

With that said, since you seem to be dealing with XML files there you may want to use PowerShell instead of CMD commands, not only because it handles ANSI and Unicode transparently, but also because it comes with a builtin XML parser.

Depending on what you want to accomplish in the end you could do things like

# get full paths for files containing <Hello> nodes
Get-ChildItem -Recurse |
  Where-Object { ([xml](Get-Content $_)).SelectNodes('//Hello') } |
  Select-Object -Expand FullName

or

# get all <Hello> nodes
Get-ChildItem -Recurse | ForEach-Object {
  ([xml](Get-Content $_)).SelectNodes('//Hello')
}

Upvotes: 2

Related Questions