这看起来是个简单的任务,但我似乎无法解决。
我有一个 LIST.TXT 文件,内容如下:
123456
555789
8888988898
12125
我有大量文件的文件名开头都带有这些数字:
123456_wedding1.jpg
123456_wedding2.doc
123456_wedding3.xls
555789_henrysales_horse.jpg
555789_goodtimes.mov
8888988898_33.avi
12125_some long description here.asx
12125_shor desc.asx
12125_shor desc2.xlsx
我声明了变量:theList、theSource 和 theDestination,我只是想将文件复制到 theDestination 文件夹(我甚至不需要子文件夹)。
以下是我尝试从其他好心人那里改编的代码:
REM @ECHO OFF
REM **************************************************
REM Adjust location of list
SET "theList=C:\2. List\List.txt"
REM Source dir
SET "theSource=C:\2. Files\"
REM Target dir
SET "theDestination=C:\2. Found\"
REM **************************************************
FOR /F "tokens=1,* delims=|" %%A IN (%theList%) DO (
ECHO.
ECHO %%A - %%B
CALL :copy "%%A - %%B"
)
ECHO.
ECHO Done^!
PAUSE
EXIT
:copy
FOR /R "%theSource%" %%F IN (*) DO (
ECHO "%%~nF" | FINDSTR /C:%1 >nul && COPY "%%~fF" "%theDestination%\%%~nxF" && EXIT /B
)
pause
EXIT /B
但是,我仍然收到此错误:
系统找不到文件 C:\2..
这似乎与文件或文件夹中的空格有关,但我无法解决。
非常感谢您的帮助
答案1
PowerShell 可以解决这个问题吗?这似乎是完成这项工作的更好的工具,而且肯定会使它更简单。例如,解决方案的骨架可以是:
$theList = "C:\2. List\List.txt"
$theSource = "C:\2. Files\"
$theDestination = "C:\2. Found\"
$toCheck = gc $theList
Get-ChildItem $theSource | Foreach-Object{
if($toCheck -match $_.BaseName)
{
write-host "matches in list file $($theList):" $_.FullName
copy-item $_.FullName -destination $theDestination
}
}
这只会复制文件。如果要移动它,请考虑使用 move-item。
如果您确实希望基本文件名的子字符串与列表文件中的条目匹配,以详细的方式使其可读并方便您修改或扩展,则以下内容可能会有所帮助:
$theList = "C:\2. List\List.txt"
$theSource = "C:\2. Files\"
$theDestination = "C:\2. Found\"
$toCheck = gc $theList
function inArrayasSub([string]$stringToCheck)
{
write-host "`tchecking: '$($stringToCheck)' exists (substring) in file " $theList
foreach ($entry in $toCheck)
{
if ($stringToCheck -match $entry)
{
write-host "`tExists based on entry: $entry"
return $true
}
}
return $false
}
Get-ChildItem $theSource | Foreach-Object{
write-host "Testing file basename: "$_.BaseName
if (inArrayasSub $_.BaseName)
{
write-host $_.BaseName "matches in list file $($theList):" $_.FullName
copy-item $_.FullName -destination $theDestination
}
write-host "======================"
}
答案2
批处理文件:
- 在下划线处从源分割所有文件
- 使用 findstr /G: 将分割的数字与列表进行比较
- 如果数字存在则复制否则回显消息
未经测试:
:: Q:\Test\2019\01\06\SU_1390824.cmd
@ECHO OFF
:: Adjust location of list
Set "theList=C:\2. List\List.txt"
:: Source dir
Set "theSource=C:\2. Files\"
:: Target dir
Set "theDestination=C:\2. Found"
For /R "%theSource%" %%A IN (*) DO For /F "delims=_" %%B in ("%%~nA") DO (
ECHO:%%B|FINDSTR /XG:"%theList%" >nul 2>&1 && (
COPY "%%~fA" "%theDestination%\%%~nxA"
)||(
Echo Not in theList: %%B , %%A
)
)
Echo Done^!
Pause
Exit /B