Get list of files that match/don't match a query in Windows

0

I have a directory tree that contains ~150 files with a specific extension (.php) organized into different folders. Some of these files are marked on line 2 to indicate a certain status. I know that this mark is always on line 2, and it always follows a specific format.

What I'm looking for is something (a command, a script, a program) that can search the directory for this mark and give me output like this, but in an easy-to-manipulate format:

example output

An ideal solution would be one that can provide a list of ALL the .php files, with line 2 of the file next to the filename. The list above does this for matched files only.

I've tried using find in a for loop:

for %f in (*.php) do find "Oracle Status" %f

But this only searches the current directory, and doesn't format it in a friendly way.

cyberbit

Posted 2016-06-15T19:04:55.830

Reputation: 227

Answers

1

If you're alright with using PowerShell, this script ought to do the job:

Get-ChildItem *.php -Recurse | ForEach-Object {
 $lines = Get-Content $_ -TotalCount 2
 If ($lines.Length -GT 1 -And $lines[1].Length -GT 1 -And $lines[1].Contains('Oracle Status:')) {
  New-Object -TypeName PSObject -Prop @{'FilePath' = $_.FullName; 'StatusLine' = $lines[1]}
 }
}

It produces output that looks like this in the console:

results

The version shown here searched for .txt files with a Status: line, but the one pasted above does what you want.

Save the script as a .ps1 file, e.g. phpstatus.ps1. If you've never run a PowerShell script before, you'll need to run this command once to allow the execution of scripts:

Set-ExecutionPolicy Unrestricted -Scope CurrentUser

Once that's done, you can invoke the script from a PowerShell prompt by typing .\ followed by its name, e.g. .\phpstatus.ps1. (Tab completion works.) Since the output is a collection of PowerShell objects, you can use standard PowerShell data management commands on them.

Ben N

Posted 2016-06-15T19:04:55.830

Reputation: 32 973

This is fantastic! I ended up making several tweaks to fit my needs (add items with status of "Untouched" if line 2 does not match, export to CSV, trim file path, sort, etc.), but you pushed me in the right direction! I suddenly love PowerShell. It's so underappreciated. <3 – cyberbit – 2016-06-16T18:31:00.223