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












2














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.










share|improve this question
























  • What have you tried so far? Also do you want the numbers included in your search or no?
    – SysEngineer
    Nov 12 '18 at 19:07






  • 1




    IF - and that is a big IF - your text is formatted as shown all the time, then take a look at the -Context parameter of Select-String. that accepts one or two [int]s for "lines before, lines after". so -Context 3,1 will grab the 3 lines before the matching line AND the 1 line after it. [grin] ///// take a look at Get-Help Select-String -Parameter Context for more info.
    – Lee_Dailey
    Nov 12 '18 at 19:52


















2














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.










share|improve this question
























  • What have you tried so far? Also do you want the numbers included in your search or no?
    – SysEngineer
    Nov 12 '18 at 19:07






  • 1




    IF - and that is a big IF - your text is formatted as shown all the time, then take a look at the -Context parameter of Select-String. that accepts one or two [int]s for "lines before, lines after". so -Context 3,1 will grab the 3 lines before the matching line AND the 1 line after it. [grin] ///// take a look at Get-Help Select-String -Parameter Context for more info.
    – Lee_Dailey
    Nov 12 '18 at 19:52
















2












2








2







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.










share|improve this question















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.







powershell






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 22:28

























asked Nov 12 '18 at 19:03









Saurabh

93




93












  • What have you tried so far? Also do you want the numbers included in your search or no?
    – SysEngineer
    Nov 12 '18 at 19:07






  • 1




    IF - and that is a big IF - your text is formatted as shown all the time, then take a look at the -Context parameter of Select-String. that accepts one or two [int]s for "lines before, lines after". so -Context 3,1 will grab the 3 lines before the matching line AND the 1 line after it. [grin] ///// take a look at Get-Help Select-String -Parameter Context for more info.
    – Lee_Dailey
    Nov 12 '18 at 19:52




















  • What have you tried so far? Also do you want the numbers included in your search or no?
    – SysEngineer
    Nov 12 '18 at 19:07






  • 1




    IF - and that is a big IF - your text is formatted as shown all the time, then take a look at the -Context parameter of Select-String. that accepts one or two [int]s for "lines before, lines after". so -Context 3,1 will grab the 3 lines before the matching line AND the 1 line after it. [grin] ///// take a look at Get-Help Select-String -Parameter Context for more info.
    – Lee_Dailey
    Nov 12 '18 at 19:52


















What have you tried so far? Also do you want the numbers included in your search or no?
– SysEngineer
Nov 12 '18 at 19:07




What have you tried so far? Also do you want the numbers included in your search or no?
– SysEngineer
Nov 12 '18 at 19:07




1




1




IF - and that is a big IF - your text is formatted as shown all the time, then take a look at the -Context parameter of Select-String. that accepts one or two [int]s for "lines before, lines after". so -Context 3,1 will grab the 3 lines before the matching line AND the 1 line after it. [grin] ///// take a look at Get-Help Select-String -Parameter Context for more info.
– Lee_Dailey
Nov 12 '18 at 19:52






IF - and that is a big IF - your text is formatted as shown all the time, then take a look at the -Context parameter of Select-String. that accepts one or two [int]s for "lines before, lines after". so -Context 3,1 will grab the 3 lines before the matching line AND the 1 line after it. [grin] ///// take a look at Get-Help Select-String -Parameter Context for more info.
– Lee_Dailey
Nov 12 '18 at 19:52














2 Answers
2






active

oldest

votes


















1














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





share|improve this answer































    0














    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:Scriptstest.txt

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





    share|improve this answer





















    • I tried below code. it generates output file but its blank. can we add like command instead of is start end? $doc = Get-Content "C:Usersa154499DesktoptestPS.txt" if(Select-String -InputObject $doc -Pattern "dwsn14626" -SimpleMatch){ $contents = [regex]::Match($doc,'(?is)(?<=bd: Scheduleb).*?(?=bd: Endb)') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
      – Saurabh
      Nov 12 '18 at 20:35












    • It is not working for me. i have many recursive entries in the file. will this script help to show multiple section in file?
      – Saurabh
      Nov 12 '18 at 20:58










    • It worked if i have only one occurrence but not working in my case because i have multiple occurrence of schedule and end statements. $doc = Get-Content "C:testPS.txt" if(Select-String -InputObject $doc -Pattern "DWSN14624"){ $contents = [regex]::Match($doc,'(?sm)(?=SCHEDULE).*?DWSN14624.*?(?=END).*') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
      – Saurabh
      Nov 12 '18 at 22:30










    • Separating the trigger Good Morning from the Start,End markers could lead to false positives in a more complex scenario than originally given. @Saurabh Did I guess right the leadinng numbers colon are not part of the file? You should append a more real life example to your question.
      – LotPings
      Nov 13 '18 at 6:35











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53268522%2fcopy-specific-portion-of-lines-from-a-text-file-to-separate-file-using-powershel%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    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





    share|improve this answer




























      1














      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





      share|improve this answer


























        1












        1








        1






        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





        share|improve this answer














        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






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 12 '18 at 20:07

























        answered Nov 12 '18 at 19:50









        LotPings

        17.9k61532




        17.9k61532

























            0














            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:Scriptstest.txt

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





            share|improve this answer





















            • I tried below code. it generates output file but its blank. can we add like command instead of is start end? $doc = Get-Content "C:Usersa154499DesktoptestPS.txt" if(Select-String -InputObject $doc -Pattern "dwsn14626" -SimpleMatch){ $contents = [regex]::Match($doc,'(?is)(?<=bd: Scheduleb).*?(?=bd: Endb)') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
              – Saurabh
              Nov 12 '18 at 20:35












            • It is not working for me. i have many recursive entries in the file. will this script help to show multiple section in file?
              – Saurabh
              Nov 12 '18 at 20:58










            • It worked if i have only one occurrence but not working in my case because i have multiple occurrence of schedule and end statements. $doc = Get-Content "C:testPS.txt" if(Select-String -InputObject $doc -Pattern "DWSN14624"){ $contents = [regex]::Match($doc,'(?sm)(?=SCHEDULE).*?DWSN14624.*?(?=END).*') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
              – Saurabh
              Nov 12 '18 at 22:30










            • Separating the trigger Good Morning from the Start,End markers could lead to false positives in a more complex scenario than originally given. @Saurabh Did I guess right the leadinng numbers colon are not part of the file? You should append a more real life example to your question.
              – LotPings
              Nov 13 '18 at 6:35
















            0














            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:Scriptstest.txt

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





            share|improve this answer





















            • I tried below code. it generates output file but its blank. can we add like command instead of is start end? $doc = Get-Content "C:Usersa154499DesktoptestPS.txt" if(Select-String -InputObject $doc -Pattern "dwsn14626" -SimpleMatch){ $contents = [regex]::Match($doc,'(?is)(?<=bd: Scheduleb).*?(?=bd: Endb)') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
              – Saurabh
              Nov 12 '18 at 20:35












            • It is not working for me. i have many recursive entries in the file. will this script help to show multiple section in file?
              – Saurabh
              Nov 12 '18 at 20:58










            • It worked if i have only one occurrence but not working in my case because i have multiple occurrence of schedule and end statements. $doc = Get-Content "C:testPS.txt" if(Select-String -InputObject $doc -Pattern "DWSN14624"){ $contents = [regex]::Match($doc,'(?sm)(?=SCHEDULE).*?DWSN14624.*?(?=END).*') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
              – Saurabh
              Nov 12 '18 at 22:30










            • Separating the trigger Good Morning from the Start,End markers could lead to false positives in a more complex scenario than originally given. @Saurabh Did I guess right the leadinng numbers colon are not part of the file? You should append a more real life example to your question.
              – LotPings
              Nov 13 '18 at 6:35














            0












            0








            0






            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:Scriptstest.txt

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





            share|improve this answer












            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:Scriptstest.txt

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






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 12 '18 at 19:34









            SysEngineer

            1236




            1236












            • I tried below code. it generates output file but its blank. can we add like command instead of is start end? $doc = Get-Content "C:Usersa154499DesktoptestPS.txt" if(Select-String -InputObject $doc -Pattern "dwsn14626" -SimpleMatch){ $contents = [regex]::Match($doc,'(?is)(?<=bd: Scheduleb).*?(?=bd: Endb)') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
              – Saurabh
              Nov 12 '18 at 20:35












            • It is not working for me. i have many recursive entries in the file. will this script help to show multiple section in file?
              – Saurabh
              Nov 12 '18 at 20:58










            • It worked if i have only one occurrence but not working in my case because i have multiple occurrence of schedule and end statements. $doc = Get-Content "C:testPS.txt" if(Select-String -InputObject $doc -Pattern "DWSN14624"){ $contents = [regex]::Match($doc,'(?sm)(?=SCHEDULE).*?DWSN14624.*?(?=END).*') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
              – Saurabh
              Nov 12 '18 at 22:30










            • Separating the trigger Good Morning from the Start,End markers could lead to false positives in a more complex scenario than originally given. @Saurabh Did I guess right the leadinng numbers colon are not part of the file? You should append a more real life example to your question.
              – LotPings
              Nov 13 '18 at 6:35


















            • I tried below code. it generates output file but its blank. can we add like command instead of is start end? $doc = Get-Content "C:Usersa154499DesktoptestPS.txt" if(Select-String -InputObject $doc -Pattern "dwsn14626" -SimpleMatch){ $contents = [regex]::Match($doc,'(?is)(?<=bd: Scheduleb).*?(?=bd: Endb)') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
              – Saurabh
              Nov 12 '18 at 20:35












            • It is not working for me. i have many recursive entries in the file. will this script help to show multiple section in file?
              – Saurabh
              Nov 12 '18 at 20:58










            • It worked if i have only one occurrence but not working in my case because i have multiple occurrence of schedule and end statements. $doc = Get-Content "C:testPS.txt" if(Select-String -InputObject $doc -Pattern "DWSN14624"){ $contents = [regex]::Match($doc,'(?sm)(?=SCHEDULE).*?DWSN14624.*?(?=END).*') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
              – Saurabh
              Nov 12 '18 at 22:30










            • Separating the trigger Good Morning from the Start,End markers could lead to false positives in a more complex scenario than originally given. @Saurabh Did I guess right the leadinng numbers colon are not part of the file? You should append a more real life example to your question.
              – LotPings
              Nov 13 '18 at 6:35
















            I tried below code. it generates output file but its blank. can we add like command instead of is start end? $doc = Get-Content "C:Usersa154499DesktoptestPS.txt" if(Select-String -InputObject $doc -Pattern "dwsn14626" -SimpleMatch){ $contents = [regex]::Match($doc,'(?is)(?<=bd: Scheduleb).*?(?=bd: Endb)') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
            – Saurabh
            Nov 12 '18 at 20:35






            I tried below code. it generates output file but its blank. can we add like command instead of is start end? $doc = Get-Content "C:Usersa154499DesktoptestPS.txt" if(Select-String -InputObject $doc -Pattern "dwsn14626" -SimpleMatch){ $contents = [regex]::Match($doc,'(?is)(?<=bd: Scheduleb).*?(?=bd: Endb)') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
            – Saurabh
            Nov 12 '18 at 20:35














            It is not working for me. i have many recursive entries in the file. will this script help to show multiple section in file?
            – Saurabh
            Nov 12 '18 at 20:58




            It is not working for me. i have many recursive entries in the file. will this script help to show multiple section in file?
            – Saurabh
            Nov 12 '18 at 20:58












            It worked if i have only one occurrence but not working in my case because i have multiple occurrence of schedule and end statements. $doc = Get-Content "C:testPS.txt" if(Select-String -InputObject $doc -Pattern "DWSN14624"){ $contents = [regex]::Match($doc,'(?sm)(?=SCHEDULE).*?DWSN14624.*?(?=END).*') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
            – Saurabh
            Nov 12 '18 at 22:30




            It worked if i have only one occurrence but not working in my case because i have multiple occurrence of schedule and end statements. $doc = Get-Content "C:testPS.txt" if(Select-String -InputObject $doc -Pattern "DWSN14624"){ $contents = [regex]::Match($doc,'(?sm)(?=SCHEDULE).*?DWSN14624.*?(?=END).*') New-Item -Path C:tmp1 -Name newtest.txt -ItemType File -Value $contents } Else{ Write-Host "Nothing Found" }
            – Saurabh
            Nov 12 '18 at 22:30












            Separating the trigger Good Morning from the Start,End markers could lead to false positives in a more complex scenario than originally given. @Saurabh Did I guess right the leadinng numbers colon are not part of the file? You should append a more real life example to your question.
            – LotPings
            Nov 13 '18 at 6:35




            Separating the trigger Good Morning from the Start,End markers could lead to false positives in a more complex scenario than originally given. @Saurabh Did I guess right the leadinng numbers colon are not part of the file? You should append a more real life example to your question.
            – LotPings
            Nov 13 '18 at 6:35


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53268522%2fcopy-specific-portion-of-lines-from-a-text-file-to-separate-file-using-powershel%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()