1.

Solve : DOS - Find multiple strings in the same line?

Answer»

I have a file which I want to extract the LINE only if it contains two strings, any ideas how to do this?  If my file contains the following strings as an example:

Code: [Select]line1:    Testing the BROWN fox jumped over a dog
line2:    Testing the brown fox and the dog cannot read
line3:    Testing2 the dog cannot read a book
line4:    Testing3 the brown fox jumped over a dog house
I just want the string that would contain the string Testing [must be first string of the line] and dog on the same line, but only the first occurrence.  And how about if I just want the last occurrence?It can be done with a couple of findstr and find filters.

The exact code depends on the actual task. 
I'll just explain here that we often see example text and create some code, and it doesn't work because the actual text had aspects that MADE it require different code.

It helps enormously to see the actual task, and if there is private data then those characters can be replaced without changing the length or makeup of the words, or the spacing.OK, I'll bite. As was mentioned the regular expression (RegEx) feature of FINDSTR can be used if all you want to do is flag lines that meet your criteria. If you're looking to actually extract the matched patterns, you;ll need a more powerful RegEx engine (Powershell or VBScript are both installed on Win 7 machines)

I put your posted sample in a file called RegEx.txt. Note: line 1 has a trailing space which is accounted for in the RegEx.

Contents of RegEx.txt:

Code: [Select]Testing the brown fox jumped over a dog
Testing the brown fox and the dog cannot read
Testing2 the dog cannot read a book
Testing3 the brown fox jumped over a dog house

From the NT command line you can run:

Code: [Select]findstr /i /r /C:"^testing.* dog " regex.txt

As it turns out, all the lines meet your requirements. The Testing pattern is at the beginning of each line and the dog pattern is both the first and last occurrence found in each line. Real data would have been more of a challenge, however the RegEx engine found in batch language is well suited for the data provided.

It's a dog's life.  Thank you, I was going about it the wrong way... I was trying to do it in multiple steps...



Discussion

No Comment Found