Powershell - how to obtain previous lines from text file?

烈酒焚心 提交于 2019-12-23 09:11:47

问题


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

回答1:


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] }


来源:https://stackoverflow.com/questions/16588795/powershell-how-to-obtain-previous-lines-from-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!