user212051
user212051

Reputation: 93

Cut string with variable numbers in windows batch script

I am trying to cut string in a file using the below code:

for %%i in (file.txt) do @set num=%%~zi
FOR /F "tokens=*" %%G IN (file.txt) DO (
CALL SET P=%%G:~%num%,4%
echo (%P%)
)

What I am doing is counting number of characters and cut only last 4 characters in the file having that file always have one line only.

But I only get this output: ~151,4

what can i do ?

Upvotes: 0

Views: 3014

Answers (2)

rojo
rojo

Reputation: 24466

Your logic is a mess. If all you want is to cut the last four characters, you don't need to capture the size of the file. You need to enable delayed expansion, set "line=%%G", and echo !line:0,~-4! or similar.

If you want to cut the last 4 chars of the final line only, leaving all other lines at full length, then you need to capture the number of lines in the file and use a little different logic.

@echo off & setlocal

set "file=test.txt"

for /f "tokens=2 delims=:" %%I in ('find /v /c "" "%file%"') do set /a linecount=%%I

for /f "tokens=1* delims=:" %%I in ('findstr /n "^" "%file%"') do (
    if %%I lss %linecount% (
        echo(%%J
    ) else (
        set "line=%%J"
        setlocal enabledelayedexpansion
        echo(!line:~0,-4!
        endlocal
    )
)

Upvotes: 0

elzooilogico
elzooilogico

Reputation: 1705

Don't need to know the length, but need Delayed Expansion

Setlocal EnableDelayedExpansion
FOR /F "tokens=*" %%G IN (file.txt) DO (
  set "P=%%G"
  set "p=!p:~,-4!"
  echo !P!
)
EndLocal

But if the file has only one line you could simply

set /p p=<"file.txt"
set "p=%p:~,-4%"
echo %P%

Upvotes: 1

Related Questions