LoginSignup
0
0

More than 3 years have passed since last update.

Powershellとcygwinでデータ連携するときは文字コード変換必須ですか?

Last updated at Posted at 2021-01-10

Windowsでもsedやgrep,awkなどUNIX由来のツールが手放せず、もうずっとcygwinを使っています。
WindowsでPowerShellのスクリプトを使うようになって、困ったことが文字コードです。
当面の結論としては、PowerShellとcygwinでデータをやりとりするときはiconvやnkfなどでの文字コード変換必須です。
その時に使うのは、Shift-JISかUTF-16で。

2021/01/13追記

コメントいただきました、ありがとうございます。
バージョンを明記するのは大事ですね。そうでした。
Windows10標準のものは 5.1ですが、最新は7なのですね。

以下は実験。

まず、お話の前提、バージョンです。OSバンドルのものです。

PS C:\> $PSVersionTable
Name                           Value
----                           -----
PSVersion                      5.1.18362.1171
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.18362.1171
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

PS C:\> uname -a
CYGWIN_NT-10.0 MyPC4 3.1.7(0.340/5/3) 2020-08-22 17:48 x86_64 Cygwin

時刻を表示させるスクリプトで試して見ます。

print_now.py
from datetime import datetime
print(datetime.now())

これをコマンドプロンプト、powershell、cygwin(mintty)でそれぞれ実行して、ファイルへリダイレクトします。すると

T:\>c:\work\date_now.py > now_cmd.txt
PS T:\> C:\work\date_now.py > now_ps.txt
$ python c:\\work\\date_now.py > now_cygwin.txt
$ file now*
now_cmd.txt:    ASCII text, with CRLF line terminators
now_cygwin.txt: ASCII text, with CRLF line terminators
now_ps.txt:     Little-endian UTF-16 Unicode text, with CRLF line terminators

PowerShellでは、リダイレクトするとUTF-16へ変換保存してくれるようです。
サイズを見てもたしかに

PS T:\> dir now*
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       2021/01/10     11:47             28 now_cmd.txt
-a----       2021/01/10     11:55             28 now_cygwin.txt
-a----       2021/01/10     11:46             58 now_ps.txt

ちなみに、標準出力に出力しつつファイル保存してくれるコマンドを使っても、

PS T:\> C:\work\date_now.py |tee now_ps_tee.txt
2021-01-10 12:09:09.078514
PS T:\> file now*
now_cmd.txt:    ASCII text, with CRLF line terminators
now_cygwin.txt: ASCII text, with CRLF line terminators
now_ps.txt:     Little-endian UTF-16 Unicode text, with CRLF line terminators
now_ps_tee.txt: Little-endian UTF-16 Unicode text, with CRLF line terminators

パイプを通した時点でUTF-16に変換されるようです。

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