Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch To Remove Character From A String

Tags:

batch-file

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

like image 866
steven Avatar asked Sep 17 '10 05:09

steven


2 Answers

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.

like image 135
paxdiablo Avatar answered Oct 06 '22 22:10

paxdiablo


This worked best for me:

@echo off
for %%x in (*.png) do  echo %%~nx

credit

like image 33
capdragon Avatar answered Oct 06 '22 23:10

capdragon