Copy specific portion of lines from a text file to separate file using powershell

Viewed 1648

I have one file in which i want to search a text and then i need to find start and end block. Then need to copy to another file. I have multiple statements in the same file.

below is an example.

1: Start
2: hello 
3: Hello world 
4: Good Morning 
5: End

I want to search "Good Morning" and then i want to copy text between start and end block to new file.

2 Answers

With a regular expression with lookarounds you can find the match
(see the regex live with different escaping \=` )

With your text in a file .\sample.txt, this snippet:

#requires -Version 3.0
[regex]::match((Get-Content .\Sample.txt -raw),"(?sm)(?<=^Start`r?`n).*?Good Morning.*?(?=`r?`nEnd)").Value
#                                                    \  lookbehind /                   \lookahead/

returns

hello
Hello world
Good Morning

The following will get you what you want. First I grabbed the contents of the txt file and put it in the $doc variable. Then using powershell's native "text" search feature I look for the string containing "Good Morning" and if that is true then using regex I grab all contents between the start and end text and create a new txt file with those contents. Below is the code.

$doc = Get-Content C:\Scripts\test.txt

      if(Select-String -InputObject $doc -Pattern "Good Morning" -SimpleMatch){
        $contents = [regex]::Match($doc,'(?is)(?<=\b\d: Start\b).*?(?=\b\d: End\b)')
            New-Item -Path C:\Scripts -Name newtest.txt -ItemType File -Value $contents
      }
      Else{
         Write-Host "Nothing Found"
      }
Related