You are not logged in.

#1 21 Oct 2020 14:31

Rekrul
Member
Registered: 17 Apr 2016
Posts: 98

Reading first few bytes of a file into a variable

I want to find the simplest, easiest way to read the first 2 bytes of a file and put them into a variable. Why? I have some comic files in CBR and CBZ format. Being a picky person, it bugs me that people will sometimes misname the files, even though it doesn't actually make a difference in opening the files, since the same program is associated with both. Since they're just normal Rar and Zip files with a different extension, I was hoping to write a script that would check to see if CBR files had "Rar!" at the start and if CBZ files had "PK" at the start, and rename the misnamed ones.

Since there doesn't seem to be a command to do this specifically, I thought I could just read the first "line" of the file into a token, then copy that into a variable and discard all but the first couple characters. As always, I started with the simplest script I could to test my theory. Of course it doesn't work.

Here's what I tried;

@echo off
for /f %%F in (test.cbz) do (
set test=%%F
set result=%test:~0,2%
echo %result%
)

I get unpredictable results. Sometimes it appears to work, sometimes it just prints "ECHO is off".

I know this isn't what it was designed for, but I figured it would read a bunch of garbage into the token and then I could strip out everything but the first two characters, which should always be text.

Offline

#2 21 Oct 2020 19:22

Shadow Thief
Member
Registered: 12 Jul 2012
Posts: 205

Re: Reading first few bytes of a file into a variable

If you only need the first line, you can redirect the file to set /p.

@echo off
<test.cbz set /p "line="
echo %line:~0,4%

Offline

#3 21 Oct 2020 19:54

RG
Member
From: Minnesota
Registered: 18 Feb 2010
Posts: 362

Re: Reading first few bytes of a file into a variable

@Rekrul,
See this post. https://ss64.org/viewtopic.php?id=985 to understand why your code is failing.


Windows Shell Scripting and InstallShield

Offline

#4 29 Oct 2020 18:20

Rekrul
Member
Registered: 17 Apr 2016
Posts: 98

Re: Reading first few bytes of a file into a variable

Shadow Thief wrote:

If you only need the first line, you can redirect the file to set /p.

Thank you! This worked great. Here's my finished script;

@echo off

for %%F in (*.cb*) do (

set Name1=%%~nxF
set Name2=%%~nF
set Extension=%%~xF

setlocal enabledelayedexpansion

<"!Name1!" set /p "Type="
set Type=!Type:~0,2!

if "!Type!"=="Ra" (if not "!Extension!"==".cbr" ren "!Name1!" "!Name2!.cbr")
if "!Type!"=="PK" (if not "!Extension!"==".cbz" ren "!Name1!" "!Name2!.cbz")

endlocal
)

I put the SetLocal command where it is so that exclamation points in filenames will be preserved.

Offline

Board footer

Powered by