Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove last characters string batch

Tags:

batch-file

hello I need to generate list of images in a txt file, but I have to remove the last character and delete duplicates

example

SDFDFDF_1.jpg
SDFDFDF_2.jpg
THGGHFG_1.jpg
THGGHFG_2.jpg

and would have to stay that way in txt list

SDFDFDF
THGGHFG

my code removes only .jpg

@echo off
if exist "sku.txt" del "sku.txt"
for /f "delims=" %%f in ('dir *.jpg /b') do echo %%~nf >> sku.txt
like image 875
Lucas Domingos Avatar asked Apr 08 '15 00:04

Lucas Domingos


2 Answers

Substrings

Batch supports syntax for taking a substring out of a string. The general syntax for this is

%string:~start,end%

Basic usage:

set test=test
echo %test:~2,3%
::st

How does this apply to your question? When a negative number is used as the end index, the substring stops that many characters before the end of the string. This behavior makes it easy to drop characters from the end of a string.

set test=test
echo %test:~0,-1%
::tes
like image 136
ankh-morpork Avatar answered Nov 16 '22 23:11

ankh-morpork


If extensions are enabled, this should work:

@echo off
if exist "sku.txt" del "sku.txt"
setlocal enabledelayedexpansion
set list=
for /f "usebackq delims=" %%f in (`dir /b *.jpg`) do (
  set xx=%%~nf
  set candidate=!xx:~0,-2!
  set n=0
  for %%i in (!list!) do (
    if "!candidate!"=="%%i" (
      set n=1
    )
  )
  if !n! EQU 0 (
    set list=!list! !candidate!
    echo !candidate! >> sku.txt
  )
)

endlocal
like image 41
jpf Avatar answered Nov 17 '22 00:11

jpf