【Powershell】ファイル内の16進数を一括で10進数に置換してみた

Powershell Powershell
この記事は約2分で読めます。

ファイル内の16進数を一括で10進数に置換してみました。

あるコマンドの出力結果の一部が16進数で表示されたので、まとめて10進数に置換できたらと思い試してみました。

広告

1.ファイル内の16進数を一括で10進数に置換する

1-1.置換前のファイルの記載

置換前のファイルは以下のようになっているとします。

cfg.general.max-address: 0x4e20
cfg.general.max-address-group: 0x9c4

1-2.置換後のファイルの記載

置換後には以下の状態になります。

cfg.general.max-address: 20000
cfg.general.max-address-group: 2500

1-3.ファイル内の16進数を一括で10進数に置換するコマンド

以下のコマンドで置換可能です。

 # 入力ファイルと出力ファイルのパス
$input_file_path = "C:\hogehoge\hex.txt"
$output_file_path = "C:\hogehoge\dec.txt"

 # 16進数 → 10進数変換処理
$pattern = "0x[0-9a-fA-F]+"
$convertedLines = Get-Content $input_file_path | ForEach-Object {
    [regex]::Replace($_, $pattern, {
        param($match)
        [convert]::ToInt32($match.Value, 16)
    })
}

 # 処理結果を別のファイルに保存
$convertedLines | Set-Content $output_file_path