-1

I am trying to return results only for lines that contain matching text via cmd.

In this case the line must match in both "Name" and "Surname".

Read though http://ss64.com/nt/findstr.html, and tried the first example

findstr "James Henry" sam.txt >sam2.txt

Unfortunately, this also returns all lines that contain just James and just Henry in them. Only a the line which contains "James" and "Henry" should be returned.

example line that should be returned

James Edgar Henry 228559

example line that should not be returned

James Peters 148825

Any assistance appreciated

David
  • 127
  • 3
  • 10

2 Answers2

1

Use the /C switch for literal string searching:

findstr /C:"James Henry" sam.txt >sam2.txt

You may need to specify /I as well if you want insensitive searches.

This is described in findstr /?:

Use spaces to separate multiple search strings unless the argument is prefixed with /C. For example, 'FINDSTR "hello there" x.y' searches for "hello" or "there" in file x.y. 'FINDSTR /C:"hello there" x.y' searches for "hello there" in file x.y.


Okay, after reading your revised question, it sounds like you need to use regular expressions:

findstr /R "James.*Henry" sam.txt >sam2.txt

If you also need to find names like "Henry Tiberius James" then I'd suggest either using a search file:

findstr /R /G:search.txt sam.txt >sam2.txt

With search.txt as:

James.*Henry
Henry.*James

Or using a better scripting language like PowerShell.

Bacon Bits
  • 30,782
  • 5
  • 59
  • 66
  • I did the /C: option but this only returns a complete matching string unless I did something wrong there (James Henry will return, but not James Edgar Henry, which should also return). I added some examples in the Question, Thanks – David May 14 '15 at 13:13
  • @David I've added to my answer. – Bacon Bits May 14 '15 at 13:29
  • I appreciate the effort. Your solution works as well. Better to have more than one way of doing something :). Will up vote your answer. Thank you – David May 14 '15 at 13:43
0

If you cannot be sure if the two words stand together or the order might be unsure, you will have to search for both of them separately:

findstr /i "\<James\>" sam1.txt | findstr /i "\<Henry\>" sam2.txt

\<means "start of a word", \> means "end of a word, so you are sure, NOT to find a guy named "Henry Jamesson"

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • You wont believe how much of a headache this has been. Your solution works perfectly. Thank you – David May 14 '15 at 13:26