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

最新のファイルからgrepしたい

Last updated at Posted at 2024-11-25

【Windowsバッチ】最新のファイルを自動取得してgrepする方法

はじめに

特定のフォルダ内で、ファイル名に特定のキーワード(例:abc)を含む .txt ファイルの中から最新のファイル を自動で取得し、その内容を findstr コマンドで検索するバッチスクリプトを作成する。

通常、最新のファイルを手動で指定するのは手間がかかるため、自動的に最新のファイルを特定し、そのファイルに対して検索を実行 できるようにする。


スクリプト

@echo off
setlocal enabledelayedexpansion

REM 作業用変数
set "latestFile="
set "latestTime=0"

REM 最新のファイルを検索(ファイル名に "abc" を含む .txt ファイル限定)
for %%F in (*abc*.txt) do (
    REM ファイルの更新日時を取得
    for /f "tokens=1,2 delims= " %%A in ('forfiles /M "%%F" /C "cmd /c echo @fdate @ftime"') do (
        REM タイムスタンプを比較する
        set "currentTime=%%A %%B"
        if "!currentTime!" GTR "!latestTime!" (
            set "latestTime=!currentTime!"
            set "latestFile=%%F"
        )
    )
)

REM 最新のファイルが見つからない場合の処理
if "%latestFile%"=="" (
    echo 更新日が最新のファイルが見つかりませんでした。
    pause
    exit /b
)

REM 最新のファイルを表示
echo 最新のファイル: %latestFile%

REM findstrでグレップ処理
REM キーワードを指定してください
set /p "keyword=検索するキーワード: "
findstr /i "%keyword%" "%latestFile%"

REM 終了
pause

スクリプトの解説

1. 最新のファイルを検索

for %%F in (*abc*.txt) do (
    for /f "tokens=1,2 delims= " %%A in ('forfiles /M "%%F" /C "cmd /c echo @fdate @ftime"') do (
        set "currentTime=%%A %%B"
        if "!currentTime!" GTR "!latestTime!" (
            set "latestTime=!currentTime!"
            set "latestFile=%%F"
        )
    )
)
  • for %%F in (*abc*.txt) do
    • abc を含む .txt ファイルを取得。
  • forfiles /M "%%F" /C "cmd /c echo @fdate @ftime"
    • 各ファイルの更新日時を取得。
  • if "!currentTime!" GTR "!latestTime!"
    • 取得した日時を比較し、最新のファイルを特定。

2. 最新のファイルが見つからない場合の処理

if "%latestFile%"=="" (
    echo 更新日が最新のファイルが見つかりませんでした。
    pause
    exit /b
)
  • latestFile が空の場合、処理を中断しエラーメッセージを表示。

3. findstr で grep 処理

set /p "keyword=検索するキーワード: "
findstr /i "%keyword%" "%latestFile%"
  • set /p "keyword=検索するキーワード: "
    • ユーザーが検索するキーワードを入力。
  • findstr /i "%keyword%" "%latestFile%"
    • 最新のファイルの中で指定キーワードを検索(大文字小文字を区別しない -i オプション付き)。

動作の流れ

  1. フォルダ内の abc を含む .txt ファイルを取得
  2. 最も新しいファイルを特定
  3. 指定したキーワードを検索
  4. 検索結果を表示

まとめ

このスクリプトを使うことで、毎回ファイル名を手入力することなく、最新のファイルを自動的に検索して findstr でgrepできる。手動でファイル名を確認する手間を省けるため、作業の効率化が可能となる。

応用例

  • 拡張子を .log に変更すれば、ログファイルの検索に活用可能。
  • *error*.txt など、特定のエラーログのみ対象にすることも可能。

このスクリプトを活用し、作業を効率化してみてほしい。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?