我已经成功地制作了一个脚本,可以过滤掉文件中的重复行并将结果保存到一个以分号分隔的变量(类似于“数组”)。我找不到任何真正好的解决方案。
@echo off
setlocal enabledelayedexpansion
rem test.txt contains:
rem 2007-01-01
rem 2007-01-01
rem 2007-01-01
rem 2008-12-12
rem 2007-01-01
rem 2009-06-06
rem ... and so on
set file=test.txt
for /f "Tokens=* Delims=" %%i in ('type %file%') do (
set read=%%i
set read-array=!read-array!;!read!
)
rem removes first trailing ";"
set read-array=!read-array:*;=!
echo !read-array!
for /f "Tokens=* Delims=" %%i in ('type %file%') do (
set dupe=0
rem searches array for the current read line (%%i) and if it does exist, it deletes ALL occurences of it
echo !read-array! | find /i "%%i" >nul && set dupe=1
if ["!dupe!"] EQU ["1"] (
set read-array=!read-array:%%i;=!
set read-array=!read-array:;%%i=!
)
rem searches array for the current read line (%%i) and if it does not exist, it adds it once
echo !read-array! | find /i "%%i" >nul || set read-array=!read-array!;%%i
)
rem results: no duplicates
echo !read-array!
的内容!read-array!
是2008-12-12;2007-01-01;2009-06-06
我现在想取出数组中的每个项目并将它们写入一个新文件,每个项目后都有换行符。例子:
2008-12-12
2007-01-01
2009-06-06
所以这就是我到目前为止想出的。
我遇到的问题是第二个循环在嵌套时for
不接受!loop!
变量作为令牌定义。%loop%
但是,如果它没有嵌套,它会接受。我这样做的原因是!read-array!
可能有未知数量的项目,因此我也计算它们。有任何想法吗?
rem count items in array
set c=0
for %%i in (!read-array!) do set /a c+=1
echo %c% items in array
for /l %%j in (1,1,%c%) do (
set loop=%%j
for /f "Tokens=!loop! Delims=;" %%i in ("!read-array!") do (
echo %%i
rem echo %%i>>%file%
)
)
exit /b