0

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 ?

2 Answers 2

1

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%
Sign up to request clarification or add additional context in comments.

3 Comments

You need %p:~,-4% - note the comma.
@KlitosKyriacou you're right, I misunderstood the OP question. Post edited.
On second thoughts you may have been right in the first place; the question is ambiguous. The OP should choose: %p:~-4% if you are interested in only the last 4 characters, or %p:~,-4% if you are interested in all except the last 4 characters.
0

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
    )
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.