Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put Md5 checksum to file name

Tags:

batch-file

cmd

There some files in directory 1.txt 2.txt 3.txt .. n.txt , i need rename them all with their md5 sum. I tired

for %f in (*.txt) do certutil -hashfile "%f" MD5 | findstr /C:2
like image 895
Gamarlinsky Avatar asked Dec 05 '25 02:12

Gamarlinsky


1 Answers

If you really need to do it from command line (from the syntax in your question) you only need an additional for /f to process the output of the certutil command executed for each file.

for %a in (*.txt) do @for /f "skip=1 tokens=1,* delims=:" %b in ('certutil -hashfile "%a" MD5') do @if "%c"=="" @echo ren "%a" "%b%~xa"

The for /f uses a skip clause to avoid the first line in the certutil's ouput (the file name) and colon as a delimiter to split lines to handle the non needed output messages (that start with CertUtil:).

That way if the line contains a colon (non needed line), it will be splitted in two (tokens=1,*), storing the left token in %b and the right one in %c.

If %c has any content this is not the line containing the hash. If %c is empty, this is the line with the hash and we rename the file.

Notes:

  • The ren command is only echoed to console. If the output seems right, remove the echo command.

  • If a file can not be read (locked or empty) the certutil only outputs error lines, so there will not be any hash and all lines will be discarded not executing the rename operation.

Anyway, doing this from command line is prone to errors. If you can, as Hackoo suggests, use a batch file.

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "tokens=1,* delims=:" %%a in ('
        cmd /q /c "for %%f in (*.txt) do certutil -hashfile "%%f" MD5&&(echo file:%%f)"
        ^| findstr /v /b /i /c:"MD5" /c:"Cert" 
    ') do (
        if "%%a"=="file" (
            set "file=%%b"
            set "extension=%%~xb"
            setlocal enabledelayedexpansion
                echo ren "!file!" "!md5: =!!extension!"
            endlocal
            set "md5="
        ) else (
            set "md5=%%a"
        )
    )

edited to include in batch code the correction pointed by sst in comments

like image 153
MC ND Avatar answered Dec 09 '25 17:12

MC ND



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!