LoginSignup
12
12

More than 5 years have passed since last update.

powershellでsed

Last updated at Posted at 2016-09-27

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

後書き

一年前以上前の記事にコメントする勇気が足りなかったんだ。。。

12
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12