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

时间:2016-05-02 12:38:29

标签: file batch-file

我写批处理文件,我有一个问题:

我想要将当前日期的所有行写到文件末尾

文本文件示例:

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

2 个答案:

答案 0 :(得分:1)

假设文本文件中的日期格式与内置环境变量%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

答案 1 :(得分:0)

由于批处理语言没有日期对象,我发现使用辅助语言很方便。例如,使用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(/\b\d+\/\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));