2017-08-28 23 views
1

我已經在各處搜索了這個地址,但是我沒有找到它,所以我想要做的事很簡單,我想計算一個文件名中的下劃線並將其放入一個變量中稍後使用它。使用蝙蝠計算文件名中的下劃線

有沒有簡單的批處理代碼來做到這一點?

+1

你有什麼嘗試過 至今? – CristiFati

回答

2
@echo off 
setlocal enabledelayedexpansion 

set filename=__example_file.bin_ 
set cnt=0 
set pos=0 

:loop 
if "!filename:~%pos%,1!"=="_" set /a cnt=%cnt%+1 
set /a pos=%pos%+1 
if not "!filename:~%pos%,1!"=="" goto loop 

echo Count: %cnt% 

這段代碼相當醜陋,但到目前爲止我找不到更好的方法。

+0

有點工作,但當我嘗試在令牌中插入%cnt%變量時,它說tdelims是意外的 –

+0

@RogerAway'for/f'循環將忽略前導分隔符並將連續分隔符作爲唯一分隔符。適合/ f的形式如下:'for/f「tokens =%cnt%delims = _」%% A in(「%filename%」)do Echo %% A' – LotPings

+0

這是我的代碼,它看起來很相似: @LotPings對於/ f「令牌=%cnt%delims = _」%% b in(「%%〜na」): –

1

一種不同的方法來計算下劃線(或更精確的元件以下劃線分隔)
是使用self expanding code

:: Q:\Test\2017\08\28\SO_45917406.cmd 
@echo off & setlocal enabledelayedexpansion 

set "FileName=example_file_name_20170828_181000.txt" 
Set i=1&Set "FileName[!i!]=%FileName:_="&Set /a i+=1&Set "FileName[!i!]=%" 

Echo Counted %i% underscore separated elements 
Set FileName 

示例輸出:

> Q:\Test\2017\08\28\SO_45917406.cmd 
Counted 5 underscore separated elements 
FileName=example_file_name_20170828_181000.txt 
FileName[1]=example 
FileName[2]=file 
FileName[3]=name 
FileName[4]=20170828 
FileName[5]=181000.txt 
0

將該溶液從@啓發xmcp:

@echo off 
Rem The srting to count in the filename is the underscrore "_" 
Rem we can of course set another one ;) 
set "MyString=_" 
setlocal enabledelayedexpansion 
@for /f "delims=" %%a in ('Dir /b "%userprofile%\Desktop"') do (
    set "filename=%%a" 
    set /a "cnt=0" 
    set /a "pos=0" 
    Call:Counting_String "!filename!" "%Mystring%" 
) 
pause & exit 
::********************************************************* 
:Counting_String <filename> <MyString> 
set "filename=%~1" 
set "string=%~2" 
if /I "!filename:~%pos%,1!"=="%Mystring%" set /a cnt+=1 
set /a pos+=1 
if not "!filename:~%pos%,1!"=="" goto Counting_String 
echo !filename!: [!cnt!] "%Mystring%" 
exit /b 
::*********************************************************