简体   繁体   中英

Extracting text (filename) out of a file with Powershell if line contains search pattern

I´ve got a problem... I´ve got a file where the content looks like

IMPORT ("$(#T_Company-BAG)\KSAKTE13","06141030.eou")
IMPORT ("$(#T_Company-Gesmbh)\KSAKTE13","06141032.eou")
IMPORT ("$(#T_Company-ITALIA)\KSAKTE13","06141038.eou")
IMPORT ("$(#T_Company-ITALIA)\KSAKTE13","06141045.eou")
IMPORT ("$(#T_Company-ITALIA)\RWRECH13","06141512.eou")

The thing i want to do is to extract the file name ( *.eou ) which is inside the last quotes and only the file names which line contains the string T_Company-ITALIA ...

The first part, extracting all lines containing the search pattern isn´t so difficult...

gc -Path C:\Scripts\Easyarchiv\level2.ebt | Select-String -Pattern T_Company-ITALIA

But i don´t know how to get only the file names ( *.eou ) out of the already selected lines...

Now I´m searching for a regex which can extract this

Here's an option without using Select-String :

Get-Content file.txt | 
where {$_ -match 'T_Company-ITALIA'} | 
foreach { $_ -replace '^.+,"(.+)"\).*$','$1'}

试试这个而不是Select-String

... | ? { $_ -match 'T_Company-ITALIA.*?,"(.*?)"' } | % { $matches[1] }

If you wanted to stay away from regular expressions (which can be hard to read, debug, and understand) you could do this:

gc file.txt | 
  foreach { 
    $splitArray = $_ -split '"'; # split at the quotation marks
    if ($splitArray[1] -match "T_Company-ITALIA") 
      {$splitArray[3]}
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM