LoginSignup
0
0

More than 5 years have passed since last update.

PHPのsscanf関数をPowerShellで使えるようにしてみた

Last updated at Posted at 2015-11-20

「PHP関数 - フォーマットされた文字列を配列・変数に - sscanf()」で紹介されているsscanf関数をPowerShellでも使えるようにしてみました。
方法は簡単で、PHPをインストールして、PowerShellから呼び出すだけです。

事前準備

1.PHPのインストール
※詳細は「PHPインストールと初期設定(Windows)」を参照

2.php.exeの格納フォルダを環境変数PATHに登録

関数定義

#PHPのsscanf関数をPowerShell用にラッピング
function sscanf($string,$format,$encoding="shift_jis"){
  $tempfile = [System.IO.Path]::GetTempFileName()
  $script = @"
<?php
  echo join("\n",sscanf("$string", "$format"))."\n";
?>
"@
  $objEncoding = [System.Text.Encoding]::GetEncoding($encoding)
  ;[System.IO.File]::WriteAllText($tempfile,$script,$objEncoding)
  php -n -f $tempfile
  del $tempfile
}

※「;[System.IO.File]」の「;」は不要(Qiitaで表示させるため)

使い方(例)

$year,$month,$day = sscanf "2015年11月21日" "%d年%d月%d日"
echo "年:$year"
echo "月:$month"
echo "日:$day"
結果
年:2015
月:11
日:21

まとめ

上記の例以外にも、コマンドプロンプトやLinux Shellの実行結果をCSV変換する等、テキスト加工が必要な場面で活躍しそうです。
実はsscanf関数自体はC言語の頃からある関数のようですが、どうしてこのような便利な関数を.NETで使えなくしたのか、少し疑問です。

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