Search code examples
powershellfile-get-contentsselect-string

PowerShell get substring in two pattern in separate file


I have read many topics but have not solved my problem, so I created a new topic.

I have the following files:

File 1:

1
2
3
ABS START
4
5
6

File 2:

7
8
9
ABS END
10
11
12

I want to get content between ABS START - ABS END. Because they are in different files so the follow command not work

$content = get-content -raw file*.txt | select-string -allmatches '(?smi)ABS START.*ABS END' 
$content.matches | foreach {$_.value}

Using for loop to read line by line seem impossible. because all file is over 2mil lines. I tried this way but It took a few days but not finish.

This is my for loop code. It can work with few file, but when i run for all file it seem cant finish

$Log = type file*
for ($i=1; $i -le $Log.Count; $i++){
   $Line = $Log[$i]
   if($Line -match "ABS START"){
      for ($j = $i; $j -le $Log.Count; $j++){
         $LineJ = $Log[$j]
         if($LineJ -match "ABS END"){
            $i = $j
            break
         }
         else{
            $Log[$j] >> $Result   
         }
      }
   }
}

Looking for your help, thank all


Solution

  • i saw your solution and i have another idea for you:

    $temp = get-content file*.txt
    $begin = $temp.indexof("ABS Start")
    $end = $temp.indexof("ABS End")
    

    now try:

    $temp[$begin..$end]
    

    i hope this helps ☺