2011-06-03 55 views

回答

0

我相信你能得到目錄中的所有文件的列表(簡單嗎?)。現在來替換部分。這裏是你如何能與電源外殼做:

type somefile.txt | %{$_ -replace "string_to_be_replaces","new_strings"}

修改它根據自己的需要。您也可以使用與其他重定向相同的方式將輸出重定向到新文件(使用:>)。

要獲取的文件列表,使用方法:

Get-ChildItem <DIR_PATH> -name

+0

我相信你可以得到目錄中所有文件的列表(簡單? - >不是真的會導致我根本不使用powershell,而是它可以在這個環境中使用的唯一一種腳本語言 – gruber 2011-06-03 15:41:02

1

也許這樣的事情

$files = Get-ChildItem "DirectoryContainingFiles" 
    foreach ($file in $files) 
    { 
    $content = Get-Content -path $file.fullname 
    $content | foreach {$_ -replace "toreplace", "replacewith"} | 
Set-Content $file.fullname 
    } 
1

如果替換字符串跨多行然後利用獲取內容不會除非將Get-Content的輸出拼接成單個字符串,否則請剪切它。它更容易使用[io.file] :: ReadAllText()在這種情況下,如:

Get-ChildItem | Where {!$_.PSIsContainer} | 
    Foreach { $txt = [IO.File]::ReadAllText($_.fullname); 
       $txt -replace $old,$new; $txt | Out-File $_} 

注意與$時候,你可能需要使用正則表達式的指令,如「(S?)」開頭以指示.也與換行符匹配。

相關問題