programing

Powershell의 텍스트 파일에 내용 삽입

skycolor 2023. 8. 25. 23:27
반응형

Powershell의 텍스트 파일에 내용 삽입

Powershell의 텍스트 파일 중간에 내용을 추가하고 싶습니다.저는 특정 패턴을 검색하고 그 뒤에 내용을 추가하고 있습니다.파일 중간에 있습니다.

현재 보유하고 있는 것은 다음과 같습니다.

 (Get-Content ( $fileName )) | 
      Foreach-Object { 
           if($_ -match "pattern")
           {
                #Add Lines after the selected pattern
                $_ += "`nText To Add"
           }
      }
  } | Set-Content( $fileName )

하지만, 이것은 작동하지 않습니다.$_가 불변이기 때문에 또는 += 연산자가 올바르게 수정하지 않기 때문에 그런 것 같습니다.

다음 컨텐츠 집합 호출에 반영될 $_에 텍스트를 추가하는 방법은 무엇입니까?

예를 들어 추가 텍스트를 출력합니다.

(Get-Content $fileName) | 
    Foreach-Object {
        $_ # send the current line to output
        if ($_ -match "pattern") 
        {
            #Add Lines after the selected pattern 
            "Text To Add"
        }
    } | Set-Content $fileName

PowerShell이 각 문자열을 줄로 종단하므로 추가 ''n''이 필요하지 않을 수 있습니다.

이거 어때:

(gc $fileName) -replace "pattern", "$&`nText To Add" | sc $fileName

저는 그것이 꽤 간단하다고 생각합니다.유일하게 명확하지 않은 것은 "패턴"으로 일치된 것을 나타내는 "$&"입니다.더 많은 정보: http://www.regular-expressions.info/powershell.html

이 문제는 어레이를 사용하여 해결할 수 있습니다.텍스트 파일은 문자열의 배열입니다.모든 요소는 텍스트 줄입니다.

$FileName = "C:\temp\test.txt"
$Patern = "<patern>" # the 2 lines will be added just after this pattern 
$FileOriginal = Get-Content $FileName

<# create empty Array and use it as a modified file... #>

$FileModified = @() 

Foreach ($Line in $FileOriginal)
{    
    $FileModified += $Line

    if ($Line -match $patern) 
    {
        #Add Lines after the selected pattern 
        $FileModified += 'add text'
        $FileModified += 'add second line text'
    } 
}
Set-Content $fileName $FileModified

XAML 텍스트 상자를 사용하여 이 작업을 수행하려고 했습니다.이 스레드는 제가 그것을 작동시키는 데 필요한 출발점을 주었습니다.

이 작업을 수행하려는 다른 사용자:

#Find and replace matched line in textbox
$TextBox.Text = ($TextBox.Text) | 
Foreach-Object {
    if ($_ -match "pattern")
    {
        #Replace matched line 
        $_ -replace "pattern", "Text To Add"
    }
}
(Get-Content $fileName) | Foreach-Object {
        if ($_ -match "pattern") 
        {
            write-output $_" Text To Add"
        }
        else{
            write-output $_
            }
    } | Set-Content $fileName

아래 스크립트는 지정된 경로에 있는 여러 파일의 패턴 뒤에 텍스트를 삽입하는 데 사용됩니다.

$fileNames = Get-ChildItem "C:\Example" -Recurse |
select -expand fullname

foreach ($FileName in $filenames) 
{
$pattern = "pattern"

[System.Collections.ArrayList]$file = Get-Content $FileName

$insertafter = @()

for ($i=0; $i -lt $file.count; $i++) {
  if ($file[$i] -match $pattern) {
    $insertafter += $i+1 #Record the position of the line after this one
  }
}

#Now loop the recorded array positions and insert the new text
$insertafter | Sort-Object -Descending | ForEach-Object { 
$file.insert($_, "text inserted after pattern") }


Set-Content $FileName $file
}

텍스트의 정확한 일치를 위한 솔루션txt,properties,pfetc 파일.

$FileName = "C:\Progress\OpenEdge\properties\fathom.properties"
$Pattern = "[Fathom]"  
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @() 
Foreach ($Line in $FileOriginal)
{   
    $FileModified += $Line
    if ( $Line.Trim() -eq $Pattern ) 
    {
        #Add Lines after the selected pattern 
        $FileModified += "Autostart=true"
        
    } 
}
Set-Content $fileName $FileModified

언급URL : https://stackoverflow.com/questions/1875617/insert-content-into-text-file-in-powershell

반응형