Windows/PowerShell&Command
PowerShell(파워쉘) 파일 내 특정문자 내용 변경하기 (Replace)
Hoonjo
2023. 6. 28. 19:30
PowerShell(파워쉘) 파일 내 특정문자 내용 변경하기 (Replace)
Replace Specific Characters in a PowerShell File (Replace)
PowerShell(파워쉘) 파일 내 특정 문자열의 내용을 변경하는 방법에 대해서 알아보겠습니다.
1. 변경 대상 확인
abc.txt 파일 내 preText 문자를 변경해 보겠습니다.
2. 명령어 입력
명령어:
Get-ChildItem -Path "C:\tistorytest" -Include "abc.txt" -Recurse | ForEach-Object{$tmp = Get-Content $_; $tmp=$tmp -Replace ("preText","afterText"); Set-Content -Encoding UTF8 $_ $tmp}
tistorytest 폴더 아래 abc.txt 파일을 찾고 preText 문자열을 afterText로 변경 후
서버와 인코딩이 다른 것을 방지하기 위해 UTF8로 인코딩을 변경하는 명령입니다.
3. 응용
Array와 foreach문을 활용해서 여러 파일 들을 한꺼번에 변경되도록 사용할 수 있습니다.
# Array
$FILELIST = "abc.txt", "abc2.txt"
foreach ($FILE in $FILELIST){
Get-ChildItem -Path "C:\tistorytest" -Include "$FILE" -Recurse | ForEach-Object{$tmp = Get-Content $_; $tmp=$tmp -Replace ("preText","afterText"); Set-Content -Encoding UTF8 $_ $tmp}
}