2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PowerShellで改行コードが混在したファイルを作成してみる

Posted at

PowerShellでテキストをファイルとして出力する際に。
改行コードを指定して出力する方法のサンプルとして、改行コードが混在したファイルをPowerShellで生成してみます。

BOMなしUTF8の文字コードが混在したファイルを作成する

PowerShellでは下記のように記述すれば、それぞれの改行コードで出力されます。

# WindowsなCRLF(0D0A)
$array = "helloworld" + "`r`n"
# LinuxなLF(0A)
$array += "helloworld" + "`n"
# 古いMacOSなCR(0D)
$array += "helloworld" + "`r"

$array | ForEach-Object { [Text.Encoding]::UTF8.GetBytes($_) } | Set-Content -Encoding Byte -Path "c:\temp\chaos.txt"

改行コードを可視化してくれるテキストエディタで表示して、出力されたファイルの改行コードを確認してみます。(画像はサクラエディタ)

image.png

もしくはUTF.GetBytesで変換したデータからでも確認できます。

image.png

やっている事としては、`r`n , `r , `nでそれぞれの改行コードを入力して、これを[Text.Encoding]GetBytesメソッドでエンコードして出力している形になります。

Encoding.GetBytes メソッド

総評

改行コードをどうこうしたい場合は、これ一つ覚えておくと便利かと思います。

2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?