powershellでファイルの中身を置換
ほぼ参考から
sedと同じことをするために
Get-Content .\hello.txt | % { $_ -replace "qii","qiita" } | Set-Content .\hello.txt
結果は、エラー(別のプロセスが掴んでいる)。
(Get-Content .\hello.txt) | %{ $_ -replace "qii","qiita" } | Set-Content .\hello.txt
とするとエラーにはなりませんが、他に問題が生じるかも?
仕組み(たぶん)
get-content はファイルの各行を要素とする配列を作る。
>get-member -input (get-content .\hello.txt)
TypeName: System.Object[]
% (foreach-object) は、パイプで配列を受け取ると、各要素に対してスクリプトブロック{}内の処理を実行する。その返値(? 次のパイプに渡す値)は配列になる。
以下だと、各要素のqiiをqiitaに置換した配列を次のパイプに渡す。
(get-content .\hello.txt) | %{ $_ -replace "qii","qiita"}
set-content は配列を、各要素を一行にしたテキストファイルを作る。
(get-content .\hello.txt) |
%{ $_ -replace "qii","qiita"} |
set-content .\hello.txt
参考?
「 Linux ならできるのに、だから Windows は...」「それ PowerShell でできるよ」 - Qiita
後書き
一年前以上前の記事にコメントする勇気が足りなかったんだ。。。