developer tip

PowerShell을 사용하여 파일에서 여러 문자열을 바꾸는 방법

optionbox 2020. 8. 25. 07:56
반응형

PowerShell을 사용하여 파일에서 여러 문자열을 바꾸는 방법


구성 파일을 사용자 지정하기위한 스크립트를 작성 중입니다. 이 파일 내에서 여러 문자열 인스턴스를 바꾸고 싶고 PowerShell을 사용하여 작업을 수행했습니다.

단일 교체에는 잘 작동하지만 여러 교체를 수행하는 것은 매번 전체 파일을 다시 구문 분석해야하고이 파일은 매우 크기 때문에 매우 느립니다. 스크립트는 다음과 같습니다.

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
    $_ -replace 'something1', 'something1new'
    } | Set-Content $destination_file

나는 이것과 같은 것을 원하지만 그것을 작성하는 방법을 모릅니다.

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
    $_ -replace 'something1', 'something1aa'
    $_ -replace 'something2', 'something2bb'
    $_ -replace 'something3', 'something3cc'
    $_ -replace 'something4', 'something4dd'
    $_ -replace 'something5', 'something5dsf'
    $_ -replace 'something6', 'something6dfsfds'
    } | Set-Content $destination_file

한 가지 옵션은 -replace작업을 함께 연결하는 것입니다. `각 라인의 끝에 다음 행에 식을 구문 분석을 계속 PowerShell을 일으키는 원인이되는 줄 바꿈을 탈출 :

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
    $_ -replace 'something1', 'something1aa' `
       -replace 'something2', 'something2bb' `
       -replace 'something3', 'something3cc' `
       -replace 'something4', 'something4dd' `
       -replace 'something5', 'something5dsf' `
       -replace 'something6', 'something6dfsfds'
    } | Set-Content $destination_file

또 다른 옵션은 중간 변수를 할당하는 것입니다.

$x = $_ -replace 'something1', 'something1aa'
$x = $x -replace 'something2', 'something2bb'
...
$x

George Howarth의 게시물이 둘 이상의 대체물과 함께 제대로 작동하도록하려면 중단을 제거하고 출력을 변수 ($ line)에 할당 한 다음 변수를 출력해야합니다.

$lookupTable = @{
    'something1' = 'something1aa'
    'something2' = 'something2bb'
    'something3' = 'something3cc'
    'something4' = 'something4dd'
    'something5' = 'something5dsf'
    'something6' = 'something6dfsfds'
}

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'

Get-Content -Path $original_file | ForEach-Object {
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
        {
            $line = $line -replace $_.Key, $_.Value
        }
    }
   $line
} | Set-Content -Path $destination_file

PowerShell 버전 3을 사용하면 replace 호출을 함께 연결할 수 있습니다.

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

줄에 'something1'또는 'something2'등을 하나만 가질 수 있다고 가정하면 조회 테이블을 사용할 수 있습니다.

$lookupTable = @{
    'something1' = 'something1aa'
    'something2' = 'something2bb'
    'something3' = 'something3cc'
    'something4' = 'something4dd'
    'something5' = 'something5dsf'
    'something6' = 'something6dfsfds'
}

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'

Get-Content -Path $original_file | ForEach-Object {
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
        {
            $line -replace $_.Key, $_.Value
            break
        }
    }
} | Set-Content -Path $destination_file

둘 이상을 가질 수있는 경우 break에서 제거하십시오 if.


파이프 라인 된 한 줄짜리 세 번째 옵션은 -replaces를 중첩하는 것입니다.

PS> ("ABC" -replace "B","C") -replace "C","D"
ADD

과:

PS> ("ABC" -replace "C","D") -replace "B","C"
ACD

이것은 실행 순서를 유지하고 읽기 쉽고 파이프 라인에 깔끔하게 맞습니다. 명시 적 제어, 자기 문서화 등에 괄호를 사용하는 것을 선호합니다. 괄호 없이도 작동하지만 얼마나 신뢰하십니까?

-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.

Please see:

help about_operators

참고URL : https://stackoverflow.com/questions/3403217/how-to-replace-multiple-strings-in-a-file-using-powershell

반응형