如何搜索和使用批量替换字符串,区分大小写 [英] how to search and replace case sensitive string using batch

查看:1443
本文介绍了如何搜索和使用批量替换字符串,区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要搜索并替换字符串,区分大小写

一样,如果我有一个文本文件崛起崛起RISE我只想要替换字符串崛起
低于code是更换所有三根弦。

请帮帮我!

  @Echo上
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION设置文件=C:\\用户\\拉瓦尔\\桌面\\ A \\ file.txt的
集/ p输入=输入一些文字:
集OldStr =崛起
设置=中newstr%输入%FOR / F令牌= 1,* delims =]%% A有('类型的文件%%|查找/ N / V,)做(
一套行= %% B
如果定义线(
拨打回声%%行:%OldStr%=%%%%中newstr GT&;> %文件%_new
)ELSE回声。
)移动/ Y%文件%_new%文件%> NUL


解决方案

这是一个已经吸引了我很长一段时间的主题。我个人的标准是,该解决方案是利用唯一的本地Windows命令的脚本,而且它是从XP起。

所有的Windows版本兼容

我已经开发了两个解决方案:1)纯批次的解决方案,我认为大约是高效的批量是可能的,以及2)混合的JScript /批的解决方案,非常强大,也非常快。

我有pretty多摒弃,取而代之的JScript中/批混合动力的纯批次解决方案,因为混合动力全正则表达式的支持更强大,而且它的速度要快得多。

1)纯批量解决方案:MODFILE.BAT

我第一次在DOSTIPS发表了这个:终极文件搜索和替换批处理工具

批次功能可以作为一个单独的实用工具,或一个较大的批处理脚本内并入本文。

假设函数在一个名为MODFILE.BAT文件要么是在当前文件夹,或其他地方你的PATH中的一个独立的实用程序,那么你的脚本变为:

 关闭@echo
SETLOCAL enableDelayedExpansion设置文件=C:\\用户\\拉瓦尔\\桌面\\ A \\ file.txt的
设置OldStr =崛起
设置=中newstr
集/ P=中newstr输入一些文字:叫ModFile%文件%OldStr中newstr

下面是ModFile函数本身。完整的文档嵌入的脚本中。我不厌其烦地优化code和消除困扰大多数批量解决方案的局限性。但也有在文档中列出了一些剩余的局限性。

 关闭@echo
:modFile文件SearchVar [ReplaceVar] [/ I]
::
::执行搜索,并在文件中的每一行替换操作。
::
:: SearchVar = A包含搜索字符串变量。
::
:: ReplaceVar = A包含替换字符串变量。
::如果ReplaceVar缺失或不那么确定
::搜索字符串替换为空字符串。
::
:: / i选项指定区分大小写的搜索。
::
::原始文件的备份与名为.bak的扩展做
::之前进行任何更改。
::
::制成替换的数目返回错误级别。
::
::如果发生错误,那么不进行改变,并
::在错误级别设置为-1。
::
::限制
:: - 文件必须使用Windows风格的行结束符< CR>< LF取代。
:: - 追踪控制字符将会从每行剥离。
:: - 最大输入线长度为1021个字符。
::
SETLOCAL enableDelayedExpansion  ::错误检查
  如果%〜2==(
    >和2回声错误:论据不足
    退出/ B -1
  )
  如果不存在%〜1(
    >和2回声错误:输入文件%〜1不存在
    退出/ B -1
  )
  2 - ; NUL PUSHD%〜1&安培;&安培; (
    POPD
    >和2回声错误:输入文件%〜1不存在
    退出/ B -1
  )
  如果没有定义%〜2(
    >和2回声错误:searchVar%2没有定义
    退出/ B -1
  )
  如果/我%〜3==/ I(
    >和2回声错误:/ I选项只能被指定为第四个参数
    退出/ B -1
  )
  如果%〜4NEQ,IF /%〜4NEQ/ I(
    >和2回声错误:无效选项%4
    退出/ B -1
  )  ::获得搜索和替换字符串
  集_search!=%〜2!
  集_replace =!%〜3!  ::编译行列表必须改变,只是退出,如果没有
  集replaceCnt = 0
  设置变化=%temp%\\ modFileChanges%随机%的.tmp
  <%〜1查找/ N%〜4_search:!=^!>%变化%||转到:清理  :: _search的计算长度
  设置海峡= A!_search!
  设置SEARCHLEN = 0
  在/ L %% A(12,-1,0)做(
    集/ ASEARCHLEN | = 1<< %% A
    在做,如果%%乙:==设置/ ASEARCHLEN&安培; =〜1<< %% A(SEARCHLEN!)海峡〜%% B,1!
  )  ::行计数+ 1
  FOR / F %% N的('发现/ V / C,^<%〜1')不设置/ A lnCnt = %% N + 1  ::备份源文件
  如果存在%〜1.bakDEL%〜1.bak
  仁%〜1%〜nx1.bak  ::初始化
  设置跳过= 2  <%〜1.bak(    %=每一个需要改变行=%
    在(!SEARCHLEN!)%%升来做FOR / F有usebackq delims = []%% L的(%变化%)做(      %=读写不需要改变=%preceding线
      对/ L %% N的(!跳!1 %% L)做(
        设置LN =
        设定/ PLN =
        如果定义如果LNLN:!〜1021 NEQ,转到:lineLengthError
        回声(!LN!
      )      %=读需要改变行=%
      设定/ PLN =
      如果定义如果LNLN:!〜1021 NEQ,转到:lineLengthError      线路%=计算长度=%
      设置海峡= A!LN!
      设置lnLen = 0
      在/ L %% A(12,-1,0)做(
        集/ AlnLen | = 1<< %% A
        在做,如果%%乙:==设置/ AlnLen&安培; =〜1<< %% A(lnLen!)海峡〜%% B,1!
      )      %=执行搜索和在线=%更换
      设置modLn =
      集/ A结束= lnLen-SEARCHLEN,求= 0
      对/ L %% o在(0 1!结束了!)做(
        如果%%ØGEQ!求!如果%〜4LN:!〜%% 0,%% L==!_搜索! (
          集/ ALEN = %%邻BEG
          FOR / F令牌= 1,2%%一中(!求求len个!!!)不设置modLn = modLn !! LN:〜!%% A,%% b!_代替!
          集/一个乞求= %% O + SEARCHLEN,replaceCnt + = 1
        )
      )
      对于一个%%在(求!)并设置modLn = modLn !! LN:!〜%%一个      %=写入修改后的行=%
      回声(!modLn!      %= prepare为下一次迭代=%
      集/跳过= %% L + 2
    )    %=读写不需要改变剩余的行=%
    对/ L %% N的(!跳!1!lnCnt!)做(
      设置LN =
      设定/ PLN =
      如果定义如果LNLN:!〜1021 NEQ,转到:lineLengthError
      回声(!LN!
    )  )>中%〜1  :清理
  德尔%变动%
退出/ B%replaceCnt%:lineLengthError
  德尔%变动%
  德尔%〜1
  仁%〜nx1.bak%〜1
  >和2回声错误:最大输入行长度超出。变化中止。
退出/ B -1


2)混合的JScript /批的解决方案:REPL.BAT

我第一次在DOSTIPS发表了这个:正则表达式搜索和替换批处理 - 轻松编辑文件!

我真的很喜欢这个工具。大多数批量脚本我作为业余爱好,但我在我的日常工作​​经常使用这个工具。这是非常强大的,快速的,但只需要很少的code。它支持常规的前pression搜索和替换,但也有一个 / L 文字选项。搜寻时默认敏感。

假设REPL.BAT是无论是在当前文件夹,或其他地方你的PATH中,那么你的code变为:

 关闭@echo
SETLOCAL enableDelayedExpansion设置文件= C:\\用户\\拉瓦尔\\桌面\\ A \\ file.txt的
设置OldStr =崛起
设置=中newstr
集/ P=中newstr输入一些文字:键入%文件%| REPL OldStr VL中newstr>中的文件%%。新
移动/ y的文件%%。新%文件%> NUL

我用选项强制文字搜索,而不是默认的正则表达式搜索,而 V 选项阅读搜索,并直接从环境变量替换值而不是传递的字符串文字。

下面是实际的REPL.BAT效用。完整的文档嵌入的脚本中。

  @if(@X)==(@ Y)@end / *无害的混合线路开头一个JScript评论:: ************文档***********
:::
::: REPL搜索替换[选项[SourceVar]
::: REPL /?
:::
:::进行全局搜索,并从输入的每一行替换操作
:::标准输入并打印结果到标准输出。
:::
:::每个参数可以用双引号括起来可选。双
:::报价不被视为参数的一部分。需要使用引号
:::如果参数包含一批令牌分隔符像空格,制表符,逗号,
:::分号。引号还应该如果参数包含一个用于
:::一批特殊字符,如&放大器;,|,等等这样的特殊字符
:::并不需要用^转义。
:::
:::如果调用/的一个参数?然后打印帮助文档
:::到标准输出。
:::
:::搜索 - 默认情况下,这是一个区分大小写的JScript(ECMA)定期
:::前pression前pressed为字符串。
:::
::: JScript的正则表达式语法文档可在
::: http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
:::替换 - 缺省是被用作替换字符串
:::每发现搜索前pression。全面支持提供了
:::提供给JScript的substituion模式代替方法。
:::一个$字面可以转义为$$。一个空字符串替换
:::必须重新psented为×$ P $。
:::
:::更换替代模式的语法在记录
::: http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
:::选项 - 用来改变行为的可选字符字符串
::: REPL的。选项​​字符不区分大小写,并可
:::以任何顺序出现。
:::
:::我 - 使得搜索不区分大小写。
:::
::: L - 搜索被视为一个字符串,而不是一个
:::定期EX pression。此外,中找到的所有$替换的
:::视为$文字。
:::
:::乙 - 搜索必须在一行的开头相匹配。
:::大多与文字搜索中使用。
:::
::: E司 - 搜索必须在一行的末尾匹配。
:::大多与文字搜索中使用。
:::
::: v - 输出搜索和替换重新present环境的名称
:::包含各自的值的变量。未定义
:::变量被当作一个空字符串。
:::
:::米 - 多行模式。标准输入的全部内容被读出并
:::在一传,而不是逐行处理。 ^锚
:::线和$开头锚一行的末尾。
:::
:::点¯x - 允许与支持扩展的替代模式语法
:::以下转义序列:
:::
::: \\\\ - 反斜杠
::: \\ b - 退格
::: \\ F - 换页
::: \\ n - 换行符
::: \\ r - 回车
::: \\ t - 水平制表
:::符\\ v - 垂直制表
::: \\ XNN - ASCII(Latin 1)字符前pressed为2进制数字
::: \\ unnnn - 统一code字前pressed为4个十六进制数字
:::
:::逃生即使当-L选项被使用的序列的支持。
:::
:::的S - 源从一个环境变量,而不是读
:::从标准输入。源环境变量的名称是
:::在选项字符串之后的下一个参数指定。
::::: ************批部分***********
关闭@echo
如果%2 EQU。 (
  如果%〜1EQU/? (
    FINDSTR^ :::%〜F0| CSCRIPT // E:JScript中// NOLOGO%〜F0^ :::
    退出/ B 0
  )其他(
    拨打:ERR论据不足
    退出/ B 1
  )

回声(%〜3 | FINDSTR /我[^ SMILEBVX]> NUL&放大器;及(
  拨打:犯错无效选项(S)
  退出/ B 1

CSCRIPT // E:JScript中// NOLOGO%〜F0%*
退出/ B 0:呃
>和2回声错误:%〜1。使用REPL /?得到帮助。
退出/ B************* JScript的部分********** /
VAR ENV = WScript.CreateObject(WScript.Shell),环境(过程)。
变参= WScript.Arguments;
VAR搜索= args.Item(0);
VAR替换= args.Item(1);
VAR的选择=G;
如果(args.length→2){
  选项​​+ = args.Item(2).toLowerCase();
}
变种多=(options.indexOf(M)GT = 0);
变种srcVar =(options.indexOf(S)GT = 0);
如果(srcVar){
  选项​​= options.replace(/ S /克,);
}
如果(options.indexOf(V)> = 0){
  选项​​= options.replace(/ V /克,);
  搜索= ENV(搜索);
  替换= ENV(替换);
}
如果(options.indexOf(L)> = 0){
  选项​​= options.replace(/ L / G,);
  搜索= search.replace(/([^ $ * +(){\\\\ |])/克,\\\\ $ 1。);
  替换= replace.replace(/ \\ $ /克,$$$$);
}
如果(options.indexOf(B)> = 0){
  选项​​= options.replace(/ b / g标准,);
  搜索=^+搜索
}
如果(options.indexOf(E)> = 0){
  选项​​= options.replace(/ E / G,);
  =搜索+$
}
如果(options.indexOf(×)> = 0){
  选项​​= options.replace(/ X /克,);
  替换= replace.replace(/ \\\\\\\\ /克,\\\\ B);
  替换= replace.replace(/ \\\\ b / g标准,\\ B);
  替换= replace.replace(/ \\\\ F / G,\\ F);
  替换= replace.replace(/ \\\\ N /克,\\ n);
  替换= replace.replace(/ \\\\ R / G,为\\ r);
  替换= replace.replace(/ \\\\吨/克,\\ t的);
  替换= replace.replace(/ \\\\ V /克,\\ V);
  替换= replace.replace(/ \\\\ X [0-9A-FA-F] {2} | \\\\ U [0-9A-FA-F] {4} /克,
    函数($ 0,$ 1,$ 2){
      返回String.fromChar code(parseInt函数(0X+ $ 0.substring(2)));
    }
  );
  替换= replace.replace(/ \\\\ B /克,\\\\);
}
VAR搜索=新的RegExp(搜索选项);如果(srcVar){
  WScript.Stdout.Write(ENV(args.Item(3))取代(搜索,替换));
}其他{
  而(!WScript.StdIn.AtEndOfStream){
    如果(多){
      WScript.Stdout.Write(WScript.StdIn.ReadAll()取代(搜索,替换));
    }其他{
      WScript.Stdout.WriteLine(WScript.StdIn.ReadLine()取代(搜索,替换));
    }
  }
}

I want to search and replace case sensitive string

like if I have rise Rise RISE in a text file I only want to replace string "rise" the code below is replace all three strings.

Kindly help me !

@Echo on
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

set file="c:\Users\rawal\Desktop\a\file.txt"
set /p Input=Enter some text:
set OldStr="rise"
set NewStr=%Input% 

for /f "tokens=1,* delims=]" %%A in ('"type %file% |find /n /v """') do (
set "line=%%B"
if defined line (
call echo %%line:%OldStr%=%NewStr%%%>> %file%_new
) ELSE echo.
)

move /Y %file%_new %file% > nul

解决方案

This is a subject that has interested me for a long time. My personal criteria is that the solution is a script that utilizes only native Windows commands, and that it be compatible with all Windows versions from XP onward.

I have developed two solutions: 1) A pure batch solution that I believe is about as efficient as is possible for batch, and 2) a hybrid JScript/batch solution that is extremely powerful and also very fast.

I have pretty much abandoned the pure batch solution in favor of the JScript/batch hybrid because the hybrid is more powerful with full regex support, and it is MUCH faster.

1) Pure batch solution: MODFILE.BAT

I first published this at DOSTIPS: The "ultimate" file search and replace batch utility

The batch function can be used as a stand-alone utility, or incorporated within a larger batch script.

Assuming the function is a stand-alone utility in a file named MODFILE.BAT that is either in your current folder, or else somewhere within your PATH, then your script becomes:

@echo off
setlocal enableDelayedExpansion

set file="c:\Users\rawal\Desktop\a\file.txt"
set "OldStr=rise"
set "NewStr="
set /p "NewStr=Enter some text: "

call ModFile "%file%" OldStr NewStr

Here is the ModFile function itself. Full documentation is embedded within the script. I've taken great pains to optimize the code, and eliminate limitations that plague most batch solutions. But there are a few remaining limitations that are listed within the documentation.

@echo off
:modFile File SearchVar [ReplaceVar] [/I]
::
::  Perform a search and replace operation on each line within File.
::
::  SearchVar = A variable containing the search string.
::
::  ReplaceVar = A variable containing the replacement string.
::               If ReplaceVar is missing or is not defined then the
::               search string is replaced with an empty string.
::
::  The /I option specifies a case insensitive search.
::
::  A backup of the original File is made with an extension of .bak
::  prior to making any changes.
::
::  The number of replacements made is returned as errorlevel.
::
::  If an error occurs then no changes are made and
::  the errorlevel is set to -1.
::
::  Limitations
::    - File must use Windows style line terminators <CR><LF>.
::    - Trailing control characters will be stripped from each line.
::    - The maximum input line length is 1021 characters.
::
setlocal enableDelayedExpansion

  ::error checking
  if "%~2"=="" (
    >&2 echo ERROR: Insufficient arguments
    exit /b -1
  )
  if not exist "%~1" (
    >&2 echo ERROR: Input file "%~1" does not exist
    exit /b -1
  )
  2>nul pushd "%~1" && (
    popd
    >&2 echo ERROR: Input file "%~1" does not exist
    exit /b -1
  )
  if not defined %~2 (
    >&2 echo ERROR: searchVar %2 not defined
    exit /b -1
  )
  if /i "%~3"=="/I" (
    >&2 echo ERROR: /I option can only be specified as 4th argument
    exit /b -1
  )
  if "%~4" neq "" if /i "%~4" neq "/I" (
    >&2 echo ERROR: Invalid option %4
    exit /b -1
  )

  ::get search and replace strings
  set "_search=!%~2!"
  set "_replace=!%~3!"

  ::build list of lines that must be changed, simply exit if none
  set "replaceCnt=0"
  set changes="%temp%\modFileChanges%random%.tmp"
  <"%~1" find /n %~4 "!_search:"=""!^" >%changes% || goto :cleanup

  ::compute length of _search
  set "str=A!_search!"
  set searchLen=0
  for /l %%A in (12,-1,0) do (
    set /a "searchLen|=1<<%%A"
    for %%B in (!searchLen!) do if "!str:~%%B,1!"=="" set /a "searchLen&=~1<<%%A"
  )

  ::count number of lines + 1
  for /f %%N in ('find /v /c "" ^<"%~1"') do set /a lnCnt=%%N+1

  ::backup source file
  if exist "%~1.bak" del "%~1.bak"
  ren "%~1" "%~nx1.bak"

  ::initialize
  set "skip=2"

  <"%~1.bak" (

    %=for each line that needs changing=%
    for %%l in (!searchLen!) do for /f "usebackq delims=[]" %%L in (%changes%) do (

      %=read and write preceding lines that don't need changing=%
      for /l %%N in (!skip! 1 %%L) do (
        set "ln="
        set /p "ln="
        if defined ln if "!ln:~1021!" neq "" goto :lineLengthError
        echo(!ln!
      )

      %=read the line that needs changing=%
      set /p "ln="
      if defined ln if "!ln:~1021!" neq "" goto :lineLengthError

      %=compute length of line=%
      set "str=A!ln!"
      set lnLen=0
      for /l %%A in (12,-1,0) do (
        set /a "lnLen|=1<<%%A"
        for %%B in (!lnLen!) do if "!str:~%%B,1!"=="" set /a "lnLen&=~1<<%%A"
      )

      %=perform search and replace on line=%
      set "modLn="
      set /a "end=lnLen-searchLen, beg=0"
      for /l %%o in (0 1 !end!) do (
        if %%o geq !beg! if %~4 "!ln:~%%o,%%l!"=="!_search!" (
          set /a "len=%%o-beg"
          for /f "tokens=1,2" %%a in ("!beg! !len!") do set "modLn=!modLn!!ln:~%%a,%%b!!_replace!"
          set /a "beg=%%o+searchLen, replaceCnt+=1"
        )
      )
      for %%a in (!beg!) do set "modLn=!modLn!!ln:~%%a!"

      %=write the modified line=%
      echo(!modLn!

      %=prepare for next iteration=%
      set /a skip=%%L+2
    )

    %=read and write remaining lines that don't need changing=%
    for /l %%N in (!skip! 1 !lnCnt!) do (
      set "ln="
      set /p "ln="
      if defined ln if "!ln:~1021!" neq "" goto :lineLengthError
      echo(!ln!
    )

  ) >"%~1"

  :cleanup
  del %changes%
exit /b %replaceCnt%

:lineLengthError
  del %changes%
  del "%~1"
  ren "%~nx1.bak" "%~1"
  >&2 echo ERROR: Maximum input line length exceeded. Changes aborted.
exit /b -1


2) Hybrid JScript/batch solution: REPL.BAT

I first published this at DOSTIPS: regex search and replace for batch - Easily edit files!

I really love this utility. Most batch scripting I do as a hobby, but I use this utility regularly in my day job. It is extremely powerful and fast, yet requires very little code. It supports regular expression search and replace, but also has an /L literal option. The search is case sensitive by default.

Assuming REPL.BAT is either in your current folder, or else somewhere within your PATH, then your code becomes:

@echo off
setlocal enableDelayedExpansion

set "file=c:\Users\rawal\Desktop\a\file.txt"
set "OldStr=rise"
set "NewStr="
set /p "NewStr=Enter some text: "

type "%file%" | repl OldStr NewStr VL >"%file%.new"
move /y "%file%.new" "%file%" >nul

I use the L option to force a literal search instead of the default regex search, and the V option to read the search and replace values directly from environment variables instead of passing string literals.

Here is the actual REPL.BAT utility. Full documentation is embedded within the script.

@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));
    }
  }
}

这篇关于如何搜索和使用批量替换字符串,区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆