PowerShell

PowerShell

Я пытаюсь проанализировать HTML-контент из нескольких текстовых файлов, выбрать определенные части каждого файла и скопировать этот контент для последующего использования и вставки в контент другого файла.

Выбранное значение будет вставлено в определенную часть содержимого другого файла, имеющего такое же имя, находящегося в другом каталоге и содержащего другое содержимое.

Файл, обновляемый выбранной частью содержимого из другого файла, будет содержать некоторое содержимое, которое необходимо сохранить и оставить неизменным.


Более детально

Предположим, у меня есть этот HTML-код изФАЙЛ-1.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="ro">
<title>YES, I love her</title>
<head>
</head>
<body>
...
<div id="coloana_centru">
  <div class="container mM" id="incadrare_text_mijloc_2" itemscope itemtype="http://schema.org/Product">
    <div align="justify">

        <!-- * * * * * START HERE * * * * * -->

        <p class="TATA"><em>At the mobile site I put as the header location in case the device isn't mobile? And then it executes the php code you gave stack..</em></p>
        <p class="MAMA">Simply check if the referrer is coming from within your site. If they are, they have already seen a page and have chosen where they want to go next</p>

        <!-- * * * * * END HERE * * * * * -->
</div>
</div>
</body>
</html>

Я хочу скопировать весь текстовый контент изФАЙЛ-1.htmlначинается с...

  1. <!-- * * * * * START HERE * * * * * -->

    вплоть до

  2. <!-- * * * * * END HERE * * * * * -->

и ввести это вФайл-2.htmlкоторый находится в другой папке в определенной области содержимого файла.

Я подозреваю, что для каждого задействованного файла, как показано в двух приведенных выше строках, эти значения могут использоваться в качестве своего рода разделителей, чтобы контролировать, откуда и куда копировать.

Это и то, и другоеФАЙЛ-1.htmlиФайл-2.htmlрядом с аннотацией:

введите описание изображения здесь

Файл-2.htmlкоторый необходимо обновить, может выглядеть так:

<section class="page_header pb-0 w-100">
    <div class="bg-overlay bg-black opacity-7"></div>
    <div class="container">
        <div class="row">
            <div class="col-md-12 page-content position-relative text-white text-center">
                <h2 class="mb-3">Blog Content</h2>
                <h6 class="mb-2 text-white text-capitalize">Creativity leads to new inventions </h6>
                <a href="../index-creative-studio.html" class="d-inline-block text-white">Home</a> <span><i class="fa fa-angle-double-right font-13"></i> Blog</span>
            </div>
        </div>
    </div>
</section>
<div id="bingo">
  <div class="container good-job" id="love" itemscope itemtype="http://schema.org/Product">
   <div class="blog-listing-inner news_item">

        <!-- * * * * * START HERE * * * * * -->

        <p class="TATA"><em> Other text 1 </em></p>
        <p class="MAMA"> Other text 2</p>

        <!-- * * * * * END HERE * * * * * -->

<div class="profile-authors heading-space-half">
    <h4 class="text-capitalize color-black mb-35px">Comments</h4>
        <div class="any-profile mb-30px">
            <div class="profile-photo"><img src="img/post6.jpg" alt="Comments"> </div>

По сути, я копирую только текст статьи из одного файла, чтобы вставить в другой файл. Этот текст, который также находится в классе, помещается между комментариями.

Проблема в том, что мне пришлось изменить 3000 файлов, а вручную я делал это только для гораздо меньших наборов файлов, поэтому пытаюсь найти более эффективный метод.

Пример каталогов файлов введите описание изображения здесь

Вы можете заменить длинные комментарии как <!-- * * * * * START HERE * * * * * -->и <!-- * * * * * END HERE * * * * * -->на что-то короткое, например <!--START1-->и<!--FINNISH1-->

ЛУЧШЕЕ РЕШЕНИЕЭТО ОДНО, использующееPOWERSHELL

$sourceFiles = Get-ChildItem 'c:\Folder1'  
$destinationFolder = 'c:\Folder2'

foreach ($file in $sourceFiles) {

$sourceContent = Get-Content $file.FullName -Raw
$contentToInsert = [regex]::match($sourceContent,"(?ms)<!--START1-->(.+)<!--FINNISH1-->").value
$destinationContent = Get-Content $destinationFolder\$($file.Name) -Raw
$destinationContent = $destinationContent -replace '(?ms)<!--START1-->(.+)<!--FINNISH1-->',$contentToInsert

Set-Content -Path $destinationFolder\$($file.Name) -Value $destinationContent -Encoding UTF8

} #end foreach file

решение1

Вероятно, есть лучший способ сделать это с помощью Windows PowerShell, но поскольку вы открыты для использования PowerShell, вот вариант, который поможет вам приступить к работе, исходя из того, что я протестировал.

PowerShell

$src = Get-ChildItem -Path "c:\Folder-1" -Filter "*.html";
$destFld = "c:\Folder-2";

$src | % { Process {
 
    If ( Test-Path "$destFld\$($_.Name)" ) { 

        Clear-Variable -Name ("a","b","c","x","y","z");
        $z = Get-Content $_.FullName -Raw;
        $y = "`t`t<!-- $((($z -split "<!--")[1]).Trim())`r`n";
        $x = "`t`t<!-- * * * * * END HERE * * * * * -->";
        $a = Get-Content "$destFld\$($_.Name)" -Raw;
        $b = "$(($a -split "<!--")[0].Trim())`r`n";
        $c = (($a -split "<!--")[2] -Split "-->")[1].Trim();
        $b | Out-File "$destFld\$($_.Name)"; 
        $y | Out-File "$destFld\$($_.Name)" -Append; 
        $x | Out-File "$destFld\$($_.Name)" -Append; 
        $c | Out-File "$destFld\$($_.Name)" -Append; 
        
        }
}};

Примеры результатов до и после

Файл-1.html (используется для обновления содержимого)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="ro">
<title>YES, I love her</title>
<head>
</head>
<body>
...
<div id="coloana_centru">
  <div class="container mM" id="incadrare_text_mijloc_2" itemscope itemtype="http://schema.org/Product">
    <div align="justify">

        <!-- * * * * * START HERE * * * * * -->

        <p class="TATA"><em>At the mobile site I put as the header location in case the device isn't mobile? And then it executes the php code you gave stack..</em></p>
        <p class="MAMA">Simply check if the referrer is coming from within your site. If they are, they have already seen a page and have chosen where they want to go next</p>

        <!-- * * * * * END HERE * * * * * -->
</div>
</div>
</body>
</html>

Файл-2.html (до обновления)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="ro">
<title>No, I do NOT love her because she too ugly</title>
<head>
</head>
<body>
...
<div id="SheTooUgly">
  <div class="container mM" id="incadrare_doc_mijloc_33" itemscope itemtype="http://schema.org/Product">
    <div align="justify">

        <!-- * * * * * START HERE * * * * * -->

        <p class="TATA"><em>Girl too ugly to love</em></p>
        <p class="MAMA">She way too ugly, yuk</p>

        <!-- * * * * * END HERE * * * * * -->
</div>
</div>
</body>
</html>

Файл-2.html (после обновления)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="ro">
<title>No, I do NOT love her because she too ugly</title>
<head>
</head>
<body>
...
<div id="SheTooUgly">
  <div class="container mM" id="incadrare_doc_mijloc_33" itemscope itemtype="http://schema.org/Product">
    <div align="justify">

        <!-- * * * * * START HERE * * * * * -->

        <p class="TATA"><em>At the mobile site I put as the header location in case the device isn't mobile? And then it executes the php code you gave stack..</em></p>
        <p class="MAMA">Simply check if the referrer is coming from within your site. If they are, they have already seen a page and have chosen where they want to go next</p>

        <!-- * * * * * END HERE * * * * * -->
</div>
</div>
</body>
</html>

Поддерживающие ресурсы

Связанный контент