寻找批处理文件以将新行插入到文本文件中

时间:2013-04-07 05:15:31

标签: batch-file command-prompt

我有一个批处理文件,它从管理门户获取图像上载目录的内容,并为每个图像生成一个包含img src属性的文本文件。

此时,每个文本文件都包含20多个图像的属性,然后我通过c#代码隐藏文件将其拉入aspx页面中的div。

我正在切换到新布局,所以我必须添加< / l i> <我>每3行之后。

我正在尝试研究如何使用批处理文件来读取包含img src的文本,并在每3行后插入该代码,但我完全丢失了.bat

3 个答案:

答案 0 :(得分:2)

使用FOR / F循环执行纯批处理可以很容易地完成,SET / A可以递增计数器,延迟扩展或CALL到子程序以及IF语句可以每次添加额外的文本第3行。

但我会使用我已编写的实用程序执行正则表达式搜索和替换。它是一个名为REPL.BAT的混合JScript /批处理脚本,适用于任何现代Windows平台。如果您了解正则表达式,它非常容易使用,并且比任何纯批处理解决方案都快得多。

它有一个M(多行)选项,允许跨换行符进行搜索和替换,以及一个允许替换文本中的转义序列的X(扩展替换)选项。

假设REPL.BAT位于当前文件夹中,或者位于PATH中的某个位置,则以下简单脚本将在原始位置的每第3行之后插入</li><li>作为新行。

编辑: 对“全部注入”计数进行了参数化,并将替换字符串中的\n更改为\r\n

@echo off
setlocal
set "file=test.txt"
set "count=3"
<"%file%" call repl "((.*\n){%count%})" "$1</li><li>\r\n" mx >"%file%.new"
move /y "%file%.new" "%file%" >nul

这是使上述脚本能够工作的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 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.
:::
:::            E - 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 "[^SMILEX]" >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("e")>=0) {
  options=options.replace(/e/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("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));
    }
  }
}

答案 1 :(得分:1)

  

使用FOR / F循环执行纯批处理可以很容易地完成,SET / A可以递增计数器,延迟扩展或CALL到子程序以及IF语句可以每次添加额外的文本第3行。

所以在这里你得到了纯粹的感觉: - )

@echo off
setlocal
set "file=test.txt"
set /a counter=0

(for /f "delims=" %%i in ('^<%file% findstr /n "^"') do call:processline "%%~i")>%file%.new
goto:eof

:processline
set "line=%~1"
set /a check=counter%%3
if %check% equ 0 if %counter% neq 0 echo(^</li^>^<li^>
set /a counter+=1
setlocal enabledelayedexpansion
echo(!line:*:=!
endlocal
exit /b

编辑:为空行添加了findstr

答案 2 :(得分:1)

@ECHO OFF
SETLOCAL
SET count=0
SET injectevery=3
FOR /f "delims=" %%Z IN ('type njacpm.txt^|findstr /n "^"') DO (
SET /a count+=1
SET line=%%Z
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO(!line:*:=!
IF !count!==%injectevery% ECHO.^</li^>^<li^>
ENDLOCAL
SET /a count=count %% %injectevery%
)

注:每dbenham评论调整20130407-1417

现在 - 如果NJACPM.TXT包含

===============================
line of text 1

line 3 - 2 was empty
: and this behind colon
but this doesn't
A line of ] many < and >varied %poison ^ characters | like "," and so on
another line
and another

now a real test %path% and !path!
what say you now?
===============================

输出是:

===============================
line of text 1

line 3 - 2 was empty
</li><li>
: and this behind colon
but this doesn't
A line of ] many < and >varied %poison ^ characters | like "," and so on
</li><li>
another line
and another

</li><li>
now a real test %path% and !path!
what say you now?
===============================

BUT:

严肃的游戏者会明白......我也试过& ......工作了!

  • njacpm.txt?现在只是一个Cotton-Pickin'分钟......