Powershel
Powershel

Reputation: 635

powershell write name of file containing string

I have following two lines in my Input file.

Sample Input file ( name of file - file.txt)

String1   value   'string2'
..
..
..
Call  string1 

Desired output : File.txt. ( i.e. Name of file )

Basically i want names of file - if it contains these two lines 1) string1 value 'string2' 2) call string1

1) and 2) above are two different lines and there could be many lines in between.

P.S. a) i am searching for 'string2' . 'string1' could be any 8 characters. I do not know 'string1' b) 'string2' will be always in single quote (') c) 'string2' will always be preceded by string 'value'

Thanks

Upvotes: 0

Views: 403

Answers (2)

Peter
Peter

Reputation: 306

The below script goes through each file in the current directory and looks for the files with the 2 lines in the content. Not sure if this meets your situation but it is not difficult to customize it to you environment.

dir *.* | foreach {if (get-content $_| Select-String -pattern  "^[A-Za-z]{8} value 'string2'","Call string1") {"$_"}}

The output (in my lab) is:

C:\Documents\ManualScripts\test.txt

test.txt is the file I created for testing this script. The content is as following:

abcdefgh value 'string2'
hello world
I love church
I love Jesus
call string1
Alibaba, sesame open the door!

To @dazedandconfused I believe your script return "String1" which is part of the second line instead of file name he/she requested. Besides your script doesn't reflect another one of his/her needs: "'string1' could be any 8 characters". Forgive me if I am wrong.

Upvotes: 0

dazedandconfused
dazedandconfused

Reputation: 3186

Try this...

 gc input.txt |?{$_ -match '.*value ''(.*)'''}|%{$matches[1]}

Upvotes: 1

Related Questions