Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find specific String in Textfile

Tags:

powershell

I know this question might be a "new guy question" but I probably made a logical mistake.

I have a text file and I want to search if it contains a string or not. I tried it as shown below but it doesn't work:

$SEL = "Select-String -Path C:\Temp\File.txt -Pattern Test" if ($SEL -eq $null) {     echo Contains String } else {     echo Not Contains String } 
like image 228
Gaterde Avatar asked Jan 26 '17 10:01

Gaterde


People also ask

How do you search for a string in a line in Python?

Python String find() method. Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1.


1 Answers

i think this is what you are trying to do:

$SEL = Select-String -Path C:\Temp\File.txt -Pattern "Test"  if ($SEL -ne $null) {     echo Contains String } else {     echo Not Contains String } 

In your example, you are defining a string called $SEL and then checking if it is equal to $null (which will of course always evaluate to false, because the string you define is not $null!)

Also, if the file contains the pattern, it will return something like:

C:\Temp\File.txt:1:Test 

So make sure to switch your -eq to -ne or swap your if/else commands around, because currently you are echoing Contains String when the $SEL is $null, which is backwards.

Check SS64 for explanations and useful examples for everything in PowerShell and cmd


Another way of checking if a string exists in the file would be:

If (Get-Content C:\Temp\File.txt | %{$_ -match "test"})  {     echo Contains String } else {     echo Not Contains String } 

but this doesn't give you an indicaion of where in the file the text exists. This method also works differently in that you are first getting the contents of the file with Get-Content, so this may be useful if you need to perform other operations on those contains after checking for your string's existence.

like image 87
Bassie Avatar answered Oct 25 '22 08:10

Bassie