6

I have a text file containing hundreds of lines of text containing database info.

I'm trying to extract the DatabaseIds for any database which is 35GB.

I would like to interrogate the file using Powershell and produce a text file containing all the matching databases.

So in essence, I would like to scan through the file, find a DatabaseSize which is 35 and then extract the corresponding DatabaseId from 3 lines previous.

I've looked all over the net but can't seem to find anything which can do this.

Example extract of text file:

ServerId = VMlinux-b71655e1
DatabaseId = db-ecb2e784
Status = completed
LocationId = 344067960796
DatabaseSize = 30

ServerId = VMlinux-0db8d45b
DatabaseId = db-cea2f7a6
Status = completed
LocationId = 344067960796
DatabaseSize = 35

ServerId = VMlinux-c5388693
DatabaseId = db-9a421bf2
Status = completed
LocationId = 344067960796
DatabaseSize = 8

etc
jleft
  • 3,457
  • 1
  • 23
  • 35
user2390040
  • 63
  • 1
  • 3
  • Just to add that I had been looking with Select-String to identify the line numbers, but could not then find a way of extracting the data given the line number: `$matches = Select-String "DatabaseSize = 35" c:\databases.txt $matches | Select LineNumber,Line` – user2390040 May 16 '13 at 13:46

1 Answers1

8

Try with something like this:

(( GC myfile.txt | 
   Select-String 'DatabaseSize = 35' -Context 3 ).context.precontext)[0]

In case of multiple match:

(GC myfile.txt | 
SELECT-STRING 'DATABASESIZE = 35' -Context 3 ) | % { ($_.context.precontext)[0] }
CB.
  • 58,865
  • 9
  • 159
  • 159
  • Thanks - that looks promising, however it only seems to give me one result. Do I need to do a foreach etc to get all the results? – user2390040 May 16 '13 at 13:55
  • An other approach would be: `Get-Content .\myfile.txt -ReadCount 6 | foreach {if ($_[4] -match 'DatabaseSize =([0-9]{1,3})') {if ($matches[1] -eq 35) {$_[1]}}}` – Davor Josipovic May 16 '13 at 14:04
  • @davor You are missing a space after `Database Size =` to match it correctly – CB. May 16 '13 at 14:14