Saurabh
Saurabh

Reputation: 19

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

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.

Upvotes: 2

Views: 2033

Answers (2)

user6811411
user6811411

Reputation:

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

Upvotes: 1

SysEngineer
SysEngineer

Reputation: 354

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

Upvotes: 0

Related Questions