tags:

views:

51

answers:

2

this may seem basic but Is there a way to create a batch to remove char from a string from a txt file. ?

If I already have this inside the .txt file

2005060.png
2005070.png
2005080.png
2005090.png
so is there a way to create a batch file that will remove the .png at the end to show only this in a new .txt file

2005060
2005070
2005080
2005090

Thanks for any help on this! :)

+1  A: 

You can do it as per the following command script:

@setlocal enableextensions enabledelayedexpansion
@echo off
set variable=2005060.png
echo !variable!
if "x!variable:~-4!"=="x.png" (
    set variable=!variable:~0,-4!
)
echo !variable!
endlocal

This outputs:

2005060.png
2005060

The magic line, of course, is:

set variable=!variable:~0,-4!

which removes the last four characters.


If you have a file testprog.in with lines it it, like:

2005060.png
1 2 3 4 5      leave this line alone.
2005070.png
2005080.png
2005090.png

you can use a slight modification:

@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "delims=" %%a in (testprog.in) do (
    set variable=%%a
    if "x!variable:~-4!"=="x.png" (
        set variable=!variable:~0,-4!
    )
    echo.!variable!
)
endlocal

which outputs:

2005060
1 2 3 4 5      leave this line alone.
2005070
2005080
2005090

Just keep in mind that it won't output empty lines (though it will do lines with spaces on them).

That may not be a problem depending on what's allowed in your input file. If it is a problem, my advice is to get your hands on either CygWin or GnuWin32 (or Powershell if you have it on your platform) and use some real scripting languages.

paxdiablo
Just tried it had no problem with it running. Thanks again!!!
steven
@steven, You should accept the answer then.
Aaron D
A: 

If your trying to read a directory of .png files and output a list without extensions? Try this:

    @echo off

    echo. > testprog.txt

    for /R "C:\Users\%USERNAME%\Documents" %%f in (*.png) do (
        echo %%~nf >> testprog.txt
        )

    start testprog.txt
Edoctoor