[MYID]
PowerShell を使用して、特定のファイル内の のすべての正確な出現箇所をMyValue
. そうする最も簡単な方法は何ですか?
14 に答える
(Get-Content file.txt) |
Foreach-Object {$_ -replace '\[MYID\]','MyValue'} |
Out-File file.txt
かっこを囲む(Get-Content file.txt)
必要があることに注意してください。
かっこがない場合、コンテンツは一度に 1 行ずつ読み取られ、同じファイルに書き込もうとする out-file または set-content に到達するまでパイプラインを流れますが、get-content によって既に開かれているため、エラー。括弧により、コンテンツの読み取り操作が 1 回 (open、read、および close) 実行されます。その後、すべての行が読み取られたときにのみ、一度に 1 つずつパイプされ、パイプラインの最後のコマンドに到達すると、ファイルに書き込むことができます。$content=content; と同じです。$コンテンツ | どこ ...
次のようなことを試すことができます:
$path = "C:\testFile.txt"
$word = "searchword"
$replacement = "ReplacementText"
$text = get-content $path
$newText = $text -replace $word,$replacement
$newText > $path
これは私が使用するものですが、大きなテキスト ファイルでは遅くなります。
get-content $pathToFile | % { $_ -replace $stringToReplace, $replaceWith } | set-content $pathToFile
大きなテキスト ファイル内の文字列を置き換える予定で、速度が懸念される場合は、System.IO.StreamReaderとSystem.IO.StreamWriterの使用を検討してください。
try
{
$reader = [System.IO.StreamReader] $pathToFile
$data = $reader.ReadToEnd()
$reader.close()
}
finally
{
if ($reader -ne $null)
{
$reader.dispose()
}
}
$data = $data -replace $stringToReplace, $replaceWith
try
{
$writer = [System.IO.StreamWriter] $pathToFile
$writer.write($data)
$writer.close()
}
finally
{
if ($writer -ne $null)
{
$writer.dispose()
}
}
(上記のコードはテストされていません。)
ドキュメント内のテキストを置き換えるために StreamReader と StreamWriter を使用するもっと洗練された方法があるかもしれませんが、それは良い出発点になるはずです。
@rominator007のクレジット
関数にラップしました(再度使用する場合があるため)
function Replace-AllStringsInFile($SearchString,$ReplaceString,$FullPathToFile)
{
$content = [System.IO.File]::ReadAllText("$FullPathToFile").Replace("$SearchString","$ReplaceString")
[System.IO.File]::WriteAllText("$FullPathToFile", $content)
}
注: 大文字と小文字は区別されません!!!!!
この投稿を参照してください:大文字と小文字を区別しない String.Replace
特定のファイル名のすべてのインスタンスで特定の行を変更する必要があったため、少し古くて異なります。
また、Set-Content
一貫した結果が返されなかったので、に頼らなければなりませんでしたOut-File
。
以下のコード:
$FileName =''
$OldLine = ''
$NewLine = ''
$Drives = Get-PSDrive -PSProvider FileSystem
foreach ($Drive in $Drives) {
Push-Location $Drive.Root
Get-ChildItem -Filter "$FileName" -Recurse | ForEach {
(Get-Content $_.FullName).Replace($OldLine, $NewLine) | Out-File $_.FullName
}
Pop-Location
}
これは、この PowerShell バージョンで私にとって最も効果的だったものです。
メジャー.マイナー.ビルド.リビジョン
5.1.16299.98
Set-Content コマンドの小さな修正。検索された文字列が見つからない場合、Set-Content
コマンドは対象ファイルを空白 (空) にします。
探している文字列が存在するかどうかを最初に確認できます。そうでない場合は、何も置き換えられません。
If (select-string -path "c:\Windows\System32\drivers\etc\hosts" -pattern "String to look for") `
{(Get-Content c:\Windows\System32\drivers\etc\hosts).replace('String to look for', 'String to replace with') | Set-Content c:\Windows\System32\drivers\etc\hosts}
Else{"Nothing happened"}