Search code examples
batch-filemd5sum

How to make md5sum command to show only hash value without a path in batch?


I have the following code to check md5sum of my images:

for /f "delims=" %%i in ('md5sum U:/imagingusb/%UserInputPath%/Image/usbimage.iso') do set output=%%i
for /f "delims=" %%i in ('md5sum /dev/sdb1') do set outputusb=%%i
echo %output%
echo %outputusb%

The output that I get is:

9a4a227e872f7130652f403c568d0081 */dev/sdb1
9a4a227e872f7130652f403c568d0081 *U:/imagingusb/dfgg/Image/usbimage.iso

How to otput only the Hash Value without path to my ISO-image? Just this:

9a4a227e872f7130652f403c568d0081 
9a4a227e872f7130652f403c568d0081

Solution

  • By default, for loops tokenize output on spaces and tabs. If you do not specify which tokens to return, you will only be able to use the first one (for /f %%A in ("this is a string") do echo %%A returns this and echo %%B returns %B instead of is).

    To get the md5 checksum by itself, you can simply remove the "delims=" in your code:

    for /f %%i in ('md5sum U:/imagingusb/%UserInputPath%/Image/usbimage.iso') do set output=%%i
    for /f %%i in ('md5sum /dev/sdb1') do set outputusb=%%i
    echo %output%
    echo %outputusb%
    

    if you needed to use the paths for something else for whatever reason, you could store them in a separate token (in this example, %%j) like this:

    for /f "tokens=1,*" %%i in ('md5sum U:/imagingusb/%UserInputPath%/Image/usbimage.iso') do set output=%%i
    for /f "tokens=1,*" %%i in ('md5sum /dev/sdb1') do set outputusb=%%i
    echo %output%
    echo %outputusb%