[Windowsバッチ/PowerShell] UNIX/Linux とのコマンド対応表


スポンサーリンク


UNIX/Linux のコマンドを、Windows のコマンドまたは PowerShell に置き換えると、どのようになるか、少し整理してみました。

UNIX/Linux だと、サクっと記述できるものが、Windows コマンドや PowerShell では、結構な記述になったりしますが、同じことを実行することができます。

表. コマンド対応表
処理内容 UNIX/Linux
Windows コマンド
PowerShell
ファイルの内容を表示。 > cat test.txt
> type test.txt
> Get-Content test.txt
文字列検索。
行頭が Hello World で始まる行を抽出。
> grep “^Hello Wolrd” test.txt
> findstr /R /C:”^Hello Wolrd” test.txt
> Select-String “^Hello Wolrd” test.txt
文字列 (Hello) を含むファイルの検索。
対象は現在ディレクトリ配下の全てで
拡張子が .txt のファイル。
> find ./ -type f -name “*.txt” -exec grep -l Hello {} \;
> findstr /M /S Hello *.txt
または
> forfiles /P .\ /S /M *.txt
  /C “cmd /c if @isdir==FALSE findstr /M Hello @path”
> Get-ChildItem -include *.txt -recurse
  | Select-String Hello | foreach { $_.Path }
1週間以内に更新されたファイルを検索。
(更新日付/サイズ/ファイル名を表示)
> find ./ -mtime -7 -type f exec ls -l {} \;
> forfiles /P .\ /S /D -7 /C
  “cmd /c if @isdir==FALSE echo @fdate @ftime @fsize @path”
> Get-ChildItem -recurse | foreach {
  if ( (Test-Path $_ -PathType Leaf) -and
    ( ((Get-Date) – $_.LastWriteTime).Days -lt 7) )
  { ($_.LastWriteTime.ToString() + ” ” + $_.Length
    + ” ” + $_.FullName) }}
テキストファイルの比較。 > diff test1.txt test2.txt
> fc test1.txt test2.txt
> Compare-Object (Get-Content test1.txt) (Get-Content test2.txt)
行数のカウント。 > wc -l test.txt
> find /C /V “DETARAME” test.txt
※ DETARAME は test.txt に存在しない文字列を指定。
> (Get-Content test.txt | Measure-Object).Count
※ Measure-Object の -Line は空行を含めないので使用しない。
ソート & 重複行除外。 > sort test.txt | uniq
uniq 相当のコマンドがないため、バッチ (sort_uniq.bat) を作成。
———————————————————————
@echo off
setlocal enabledelayedexpansion
for /F "tokens=*" %%a in ('sort %1') do (
  if not "!PREV!" == "%%a" (
    echo %%a
  )
  set PREV=%%a
)
———————————————————————
上記バッチを以下のようにして実行。
> sort_uniq.bat test.txt
> Get-Content test.txt | Sort-Object | Get-Unique
システム時間を表示。
(yyyy/mm/dd HH:MM:SS 形式)
> date +”%Y/%m/%d %H:%M:%S”
> set T=%TIME:~0,8%
> echo %DATE% %T: =0%
※ TIME は HH:MM:SS.mm と末尾にミリ秒が付与されるため、
  先頭 8 文字のみ取得。
  さらに 0~9 時の間は先頭が半角スペース (” 9:12:33″ 等)
  となるため、半角スペースを 0 に置換。
> Get-Date -uFormat “%Y/%m/%d %H:%M:%S”
ホスト名を表示。 > hostname
> hostname
> (Get-WmiObject -Class Win32_OperatingSystem).CSName
 
スポンサーリンク