Windows Batch - delete last characters from variable

1.9k views Asked by At

I need to delete the last 3 characters from a variable in Windows batch

set string=abcdefghij

I need the following output:

abcdefg

I can delete the first 3 characters from the variable using this:

set newstring=%string:~3,100%
echo %newstring%

Output:

defghij

But how can I delete the last 3 characters from the string - and store the result into a variable?

I can show the string without the last 3 characters by using sed (from GnuWin32) but I also need to store the result into another variable. I need a better solution than storing the result in a file and then reading the file into a variable (set /p newstring=<file.txt)

Later note: This question is very different, it needs removing last characters from a multi-line text, while I need removing last characters from a variable.

1

There are 1 answers

1
uncletall On BEST ANSWER

Just use negative index

set longtext=1234567890
:: Remove last 3 characters
echo %longtext:~0,-3%
:: show last three characters
echo %longtext:~-3%

Output:

1234567
890