Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - how to obtain previous lines from text file?

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
like image 371
user2390040 Avatar asked May 16 '13 13:05

user2390040


People also ask

How do I go to a previous line in PowerShell?

To move to the beginning of a line, press Home . To move to the end of a line, press End . If lines were added, press Home or End twice to move to the beginning or end of the lines.

How do I read the first 10 lines of a file in PowerShell?

In PowerShell to select first 10 lines of file, use Get-Content command with Select -First parameter with value 10. Here -First 10 show top 10 lines of the file.

How do I get data from a file in PowerShell?

When you want to read the entire contents of a text file, the easiest way is to use the built-in Get-Content function. When you execute this command, the contents of this file will be displayed in your command prompt or the PowerShell ISE screen, depending on where you execute it.


1 Answers

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] }
like image 122
CB. Avatar answered Sep 20 '22 16:09

CB.