PARSING: Copy lines from several files into a single point of other html files

Suzana Eree 811 Reputation points

hello, maybe someone can help me. I have a lot of html files in Folder-1 and the same number of files in Folder-2. The name of the files is the same on both folders, only the content of them is different. As you can see in this image what I want to do is to copy the lines from <!--START--> to <!--FINNISH --> and paste them to other files from second folder, in html files, in the point PUT-HERE-THE-CODE

You have to know that the content of <!--START--> to <!--FINNISH --> is different on all pages, so only this 2 words are repeated in all files, the links are different. And in the Folder-2, the only part that repeats in all files is PUT-HERE-THE-CODE


This are the code lines from both files:


Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,435 questions
0 comments No comments
{count} votes

Accepted answer
  1. Suzana Eree 811 Reputation points

    I find The solution: Thanks for regex.

    $sourceFiles = Get-ChildItem 'c:\Folder1'  
    $destinationFolder = 'c:\Folder2'
    foreach ($file in $sourceFiles) {
    $sourceContent = Get-Content $file.FullName -Raw
    $contentToInsert = [regex]::match($sourceContent,"(?ms)\<!--START--\>(.+)\<!--FINNISH --\>").value
    $destinationContent = Get-Content $destinationFolder\$($file.Name) -Raw
    $destinationContent = $destinationContent -replace 'PUT-HERE-THE-CODE',$contentToInsert
    Set-Content -Path $destinationFolder\$($file.Name) -Value $destinationContent -Encoding UTF8
    } #end foreach file
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Rich Matheisen 45,431 Reputation points

    I'll leave you to deal with getting the file names and directories into the code, but this pair of regular expressions should do the replacement:

    $f1text = get-content .\f1.txt -raw
    $f2text = get-content .\f2.txt -raw
    $f3text = ""
    if ($f1text -cmatch "(?ms)\<!--START--\>(.+)\<!--FINNISH --\>"){
        $p = $Matches[1]
        if ($f2text -cmatch "(?ms)PUT-HERE-THE-CODE"){
            $f3text = $f2 -creplace "PUT-HERE-THE-CODE", "$p"
    1 person found this answer helpful.
    0 comments No comments

  2. Suzana Eree 811 Reputation points

    Thank you, yes, but your code will make a replacement only in 2 files, f1.txt and f2.txt. But I have 1300 files in Folder-1 and 1300 files in Folder-2. So I want to change all at once. How can I do that ?

    0 comments No comments