批处理文件将一些行从一个文本文件复制到另一个文本档案



我写批处理文件,遇到了一个问题:

我想写从当前日期到文件结束的所有行

文本文件示例:

not copy this line.
not copy this line.
not this line.
5/02/2016  10 20 30 45 05 56 70 (from here )
5/03/2016  10 20 30 45 05 56 70 
5/04/2016  10 20 30 45 05 56 70 
5/05/2016  10 20 30 45 05 56 70

我的代码:

@ECHO OFF
set filename=abc.txt
set filename2=outFile.txt
set find=find.txt
set sourceFolder=c:1
IF EXIST "%find%" DEL "%find%"
IF EXIST "%filename2%" DEL "%filename2%"
IF EXIST "SAMPLE_text01.txt" DEL "SAMPLE_text01.txt"
set currentdate=%date%
set newdate=%currentdate:~5,11%
echo %newdate% >> %sourceFolder%%find%
findstr /g:%sourceFolder%%find% %sourceFolder%%filename% > %sourceFolder%%filename2%
set count=0
for /f "tokens=*" %%i in ('findstr /g:%sourceFolder%%find% 
"%sourceFolder%%filename%"') do (
    rem echo count is %count%
    set /a count+=1
    echo.%* >> temp.txt
)
pause

假设文本文件中的日期格式与内置环境变量%DATE%返回的格式相同,则以下脚本(我们称之为lines-from-today-on.bat)应该适用:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define constants here:
set "INFILE=%~1"
if not defined INFILE set "INFILE=%~dpn0.txt"
set "OUTFILE=%~2"
if not defined OUTFILE set "OUTFILE=con"
> "%OUTFILE%" (
    set "FLAG="
    for /F "delims=" %%L in ('
        findstr /N /R "^" "%INFILE%"
    ') do (
        set "LINE=%%L"
        setlocal EnableDelayedExpansion
        for /F "tokens=1 eol= " %%F in ("!LINE:*:=!") do (
            endlocal
            if "%%F"=="%DATE%" (
                set "FLAG=#"
            )
            setlocal EnableDelayedExpansion
        )
        if defined FLAG echo(!LINE:*:=!
        endlocal
    )
)
endlocal
exit /B

要使用它,请通过提供输入文件作为命令行参数(本例中当前目录中的文本文件sample.txt)来调用它:

lines-from-today-on.bat sample.txt

这将在控制台上显示提取的行。要将它们输出到另一个文本文件(此处为return.txt)中,请提供另一个参数:

lines-from-today-on.bat sample.txt return.txt

由于Batch语言没有日期对象,我发现使用有日期对象的辅助语言很方便。例如,使用JScript,您可以对日期对象使用小于/大于比较,并且日期的格式设置更宽容一些。(文本文件总是有一个零填充的日期和一个非零填充的月份吗?JScript的new Date()构造函数的工作方式都是一样的。)

用.bat扩展保存这个,看看你怎么想。

@if (@CodeSection == @Batch) @then
@echo off & setlocal
set "in=abc.txt"
set "out=outfile.txt"
set "found="
rem // redirect output to outfile
> "%out%" (
    rem // for each line of the text file...
    for /f "usebackq delims=" %%I in ("%in%") do (
            rem // use JScript to check whether line contains a date of today or future
            if not defined found call :isCurrent "%%~I" && set "found=1"
            if defined found echo(%%I
        )
    )
)
goto :EOF
:isCurrent <date>
cscript /nologo /e:JScript "%~f0" "%~1"
exit /b %ERRORLEVEL%
@end // end batch / begin JScript hybrid code
try {
    var today = new Date(new Date().toDateString()), // truncate to midnight
        otherDate = new Date(WSH.Arguments(0).match(/bd+/d+/d+b/)[0]);
}
catch(e) { WSH.Quit(1); } // exits non-zero if argument contains no dates
// exits non-zero if otherDate is earlier than today
WSH.Quit(!(today <= otherDate));

最新更新