How can I remove lines after a specific character in multiple files using a package?

I am trying to remove some characters after _1 and rename the file but am stuck. let me list the filenames of the samples so they understand.

aero_name_1_3_7.png
glik_trol_1_5_2_9_5.png
this_that_1_3_1_9.png
....... and so on. 

      

So my filenames contain the exact format but different names, so I decided to use tokens and divisible. After renaming, my files should look like aero_name_1.png, glik_trol_1.png, this_that_1.png Here is a piece of a bat I wrote, but it won't work. If anyone could guess it would be great.

for /F "tokens=1-4,* delims=_" %%a in ('dir /A-D /B "*.png"') do (
  move "%%a_%%b" "%%a%%~xb"
)

      

thank

0


source to share


2 answers


Looking at your second filename, this is what the FOR / F loop has:

%%a=glik
%%b=trol
%%c=1
%%d=5
%%e=2_9_5.png

      

So your MOVE command becomes:

move "glik_trol" "glik"

      

Please note that %%b

there is no extension

you can use



for /f "tokens=1-3* delims=_" %%a in ('dir /a-d /b *.png') do (
  move "%%a_%%b_%%c_%%d" "%%a_%%b_%%c%%~xd"
)

      

If you're comfortable with regular expressions, you can use my handy utility JREN.BAT - a hybrid JScript / batch script that renames files by executing find and replace regex on the name. JREN.BAT is a pure script that runs natively on any Windows machine from XP onwards. This is a very convenient way to perform very precise renaming operations.

Assuming you're JREN.BAT in your current directory, or better yet, somewhere within your PATH:

jren "^([^_]+_[^_]+_[^_]+)_.*(\.png)$" "$1$2" /i

      

No batch required. If you use a command in a script package then you must prefix the command CALL

because JREN is also a script package.

+1


source


From your "remove some characters after _1" requirement, it seems like the best solution would be to use a substring of the substring . Not sure if you would benefit from this, but this solution will allow for a variable number of underscores before _1

, as opposed to the more static usage "delims=_"

you are currently using.

Substring substitution is great for removing details from the beginning (e.g. set "var=%var:*_1=%"

), but trailing off the end is a little more difficult. One way to do this is to insert rem

in replacement.



Try the following:

@echo off
setlocal

for %%I in (*.png) do call :ren "%%~I"

goto :EOF

:ren <filename>
set "pngfile=%~1"
echo "%pngfile%" | find "_1" >NUL || goto :EOF
set pngfile=%pngfile:_1=&rem.%
echo ren "%~1" "%pngfile%_1.png"

      

+1


source







All Articles