【问题标题】:Windows batch script help for checking last line of the file用于检查文件最后一行的 Windows 批处理脚本帮助
【发布时间】:2013-05-16 08:47:21
【问题描述】:

我有几百个文件,其中大部分在末尾(结束行)包含“exit”。并非所有文件的末尾都有这个“exit”。如何检查内容文件的最后一行,如果是 'exit' 则将其删除?

【问题讨论】:

  • 如果您使用的是服务器 2k3 或更高版本,您应该在资源工具包中找到 HEAD.EXE 和 TAIL.EXE。尝试使用这些。 TAIL 会从文件的末尾返回指定的行数,HEAD 会从文件的开头返回指定的行数。

标签: batch-file window


【解决方案1】:

我编写了一个名为 REPL.BAT 的混合 JScript/批处理实用程序,它使这项任务非常简单,而且速度非常快。该实用程序读取标准输入,执行任何正则表达式搜索和替换,并将输出写入 stout。

该实用程序是一个脚本,可在任何现代版本的 Windows(从 XP 开始)上运行,并且不需要安装任何 3rd 方工具。

以下批处理脚本处理给定路径中的所有文件,并且仅当每个文件的最后一行是单词 exit 且没有其他字符时才删除它。我使用I 选项使搜索不区分大小写。还需要M 选项以允许跨多行搜索。正则表达式可以根据需要轻松改进。例如,如果最后一行包含带有空格的 EXIT,您也可以匹配并删除它。

@echo off
for %%F in (\somePath\*) do (
  type "%%F"|repl "^exit\r?\n?(?!\S|\s)" "" im >"%%F.new"
  move /y "%%F.new" "%%F" >nul
)

REPL.BAT 文件必须位于您当前的文件夹(您从中运行的文件夹)中,或者更好的是,位于您的 PATH 文件夹之一中。

这是 REPL.BAT 脚本。我发现它对于这么小的脚本非常有用。完整的文档嵌入在脚本中。

@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment

::************ Documentation ***********
:::
:::REPL  Search  Replace  [Options  [SourceVar]]
:::REPL  /?
:::
:::  Performs a global search and replace operation on each line of input from
:::  stdin and prints the result to stdout.
:::
:::  Each parameter may be optionally enclosed by double quotes. The double
:::  quotes are not considered part of the argument. The quotes are required
:::  if the parameter contains a batch token delimiter like space, tab, comma,
:::  semicolon. The quotes should also be used if the argument contains a
:::  batch special character like &, |, etc. so that the special character
:::  does not need to be escaped with ^.
:::
:::  If called with a single argument of /? then prints help documentation
:::  to stdout.
:::
:::  Search  - By default this is a case sensitive JScript (ECMA) regular
:::            expression expressed as a string.
:::
:::            JScript regex syntax documentation is available at
:::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
:::  Replace - By default this is the string to be used as a replacement for
:::            each found search expression. Full support is provided for
:::            substituion patterns available to the JScript replace method.
:::            A $ literal can be escaped as $$. An empty replacement string
:::            must be represented as "".
:::
:::            Replace substitution pattern syntax is documented at
:::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
:::  Options - An optional string of characters used to alter the behavior
:::            of REPL. The option characters are case insensitive, and may
:::            appear in any order.
:::
:::            I - Makes the search case-insensitive.
:::
:::            L - The Search is treated as a string literal instead of a
:::                regular expression. Also, all $ found in Replace are
:::                treated as $ literals.
:::
:::            B - The Search must match the beginning of a line.
:::                Mostly used with literal searches.
:::
:::            E - The Search must match the end of a line.
:::                Mostly used with literal searches.
:::
:::            V - Search and Replace represent the name of environment
:::                variables that contain the respective values. An undefined
:::                variable is treated as an empty string.
:::
:::            M - Multi-line mode. The entire contents of stdin is read and
:::                processed in one pass instead of line by line. ^ anchors
:::                the beginning of a line and $ anchors the end of a line.
:::
:::            X - Enables extended substitution pattern syntax with support
:::                for the following escape sequences:
:::
:::                \\     -  Backslash
:::                \b     -  Backspace
:::                \f     -  Formfeed
:::                \n     -  Newline
:::                \r     -  Carriage Return
:::                \t     -  Horizontal Tab
:::                \v     -  Vertical Tab
:::                \xnn   -  Ascii (Latin 1) character expressed as 2 hex digits
:::                \unnnn -  Unicode character expressed as 4 hex digits
:::
:::                Escape sequences are supported even when the L option is used.
:::
:::            S - The source is read from an environment variable instead of
:::                from stdin. The name of the source environment variable is
:::                specified in the next argument after the option string.
:::

::************ Batch portion ***********
@echo off
if .%2 equ . (
  if "%~1" equ "/?" (
    findstr "^:::" "%~f0" | cscript //E:JScript //nologo "%~f0" "^:::" ""
    exit /b 0
  ) else (
    call :err "Insufficient arguments"
    exit /b 1
  )
)
echo(%~3|findstr /i "[^SMILEBVX]" >nul && (
  call :err "Invalid option(s)"
  exit /b 1
)
cscript //E:JScript //nologo "%~f0" %*
exit /b 0

:err
>&2 echo ERROR: %~1. Use REPL /? to get help.
exit /b

************* JScript portion **********/
var env=WScript.CreateObject("WScript.Shell").Environment("Process");
var args=WScript.Arguments;
var search=args.Item(0);
var replace=args.Item(1);
var options="g";
if (args.length>2) {
  options+=args.Item(2).toLowerCase();
}
var multi=(options.indexOf("m")>=0);
var srcVar=(options.indexOf("s")>=0);
if (srcVar) {
  options=options.replace(/s/g,"");
}
if (options.indexOf("v")>=0) {
  options=options.replace(/v/g,"");
  search=env(search);
  replace=env(replace);
}
if (options.indexOf("l")>=0) {
  options=options.replace(/l/g,"");
  search=search.replace(/([.^$*+?()[{\\|])/g,"\\$1");
  replace=replace.replace(/\$/g,"$$$$");
}
if (options.indexOf("b")>=0) {
  options=options.replace(/b/g,"");
  search="^"+search
}
if (options.indexOf("e")>=0) {
  options=options.replace(/e/g,"");
  search=search+"$"
}
if (options.indexOf("x")>=0) {
  options=options.replace(/x/g,"");
  replace=replace.replace(/\\\\/g,"\\B");
  replace=replace.replace(/\\b/g,"\b");
  replace=replace.replace(/\\f/g,"\f");
  replace=replace.replace(/\\n/g,"\n");
  replace=replace.replace(/\\r/g,"\r");
  replace=replace.replace(/\\t/g,"\t");
  replace=replace.replace(/\\v/g,"\v");
  replace=replace.replace(/\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}/g,
    function($0,$1,$2){
      return String.fromCharCode(parseInt("0x"+$0.substring(2)));
    }
  );
  replace=replace.replace(/\\B/g,"\\");
}
var search=new RegExp(search,options);

if (srcVar) {
  WScript.Stdout.Write(env(args.Item(3)).replace(search,replace));
} else {
  while (!WScript.StdIn.AtEndOfStream) {
    if (multi) {
      WScript.Stdout.Write(WScript.StdIn.ReadAll().replace(search,replace));
    } else {
      WScript.Stdout.WriteLine(WScript.StdIn.ReadLine().replace(search,replace));
    }
  }
}

【讨论】:

    【解决方案2】:
       setlocal enabledelayedexpansion 
       for /f "delims=" %%Z in ('dir /s /b /a-d .') do (
           for /f "delims=" %%a in (%%Z) do  set last_line=%%a
           echo !last_line! | find "exit" && del /f /q %%Z
        )
        endlocal
    

    编辑(foxidrive 读起来比我仔细):

      @echo off
    
      setlocal enabledelayedexpansion 
       for /f "delims=" %%Z in ('dir /s /b /a-d') do (
    
           set /a counter=1
           set "yes=no"
           for /f "usebackq delims=" %%a in ("%%Z") do  set last_line=%%a&& set /a counter=counter+1
           echo !last_line! | find /I "exit" >nul&& set "yes=yes"
           if "!yes!" equ "yes" (
              break >"%%Z.tmp"
              for /f "usebackq delims=" %%a in ("%%Z") do (
                 set /a counter=counter-1
                 if "!counter!" neq "1" (
                    endlocal
                    echo %%a | find "ECHO is off.">nul&&echo\>>"%%Z.tmp"   
                    echo %%a | find "ECHO is off.">nul||echo %%a>>"%%Z.tmp"
                )
              )
              echo "Exit" found in  at the end of --%%Z--
              copy /y "%%Z.tmp" "%%Z" >nul 
           )
        )
        endlocal
    

    edit:工作和一点点改进。仍然不能处理空行,但现在更好了。

    【讨论】:

    • 我认为对象是删除exit而不是删除文件。
    【解决方案3】:

    对于sed“仅”:

    for %i in (*) do @sed -i"%~i.bak" "$ {s/exit/exit/i;/exit/d}" "%~i"
    

    【讨论】:

      【解决方案4】:

      从@npocmaka 借用代码并使用 GNUsed 那么这应该非常健壮,并且可以保留空白行并处理长文件名等。它处理整个目录树。未经测试。

      @echo off
      setlocal enabledelayedexpansion 
      for /f "delims=" %%Z in ('dir /s /b /a-d') do (
         for /f "delims=" %%a in ('type "%%Z"') do set "last_line=%%a"
           echo !last_line! | find /i "exit" >nul && (
              sed $d "%%Z" > "%%Z.tmp"
              move /y "%%Z.tmp" "%%Z" >nul
       )
      )
      endlocal
      

      【讨论】:

      • 实际上我的 Windows 机器上没有安装 sed,我无法安装它,因为我为一些跨国公司工作,他们不安装任何软件,除了他们信任和购买的软件。跨度>
      【解决方案5】:
      @echo off
      setlocal EnableDelayedExpansion
      
      rem "I have a few hundred files"
      for %%a in (*.*) do (
         rem "most of which contains 'exit' at the end line."
         set "lastLine="
         (for /F "usebackq delims=" %%b in ("%%a") do (
            if not defined lastLine (
               set "lastLine=%%b"
            ) else (
               echo(!lastLine!
               set "lastLine=%%b"
            )
         )) > "%%~Na.tmp"
         rem "Not all of the files have this 'exit' at the end."
         rem "How can I check the content of last line of the files"
         if "!lastLine!" equ "exit" (
            rem "and then remove it if it's 'exit'?"
            move /Y "%%~Na.tmp" "%%a"
         ) else (
            del "%%~Na.tmp"
         )
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-16
        • 2011-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多