windows bat script find替换文件夹和子文件夹中的每个文件

时间:2013-06-28 13:00:59

标签: windows batch-file replace find

首先,我要说的是我完全不熟悉脚本。

我正在尝试开发一个脚本,它将找到一个给定的字符串并用另一个给定的字符串替换它。必须对文件夹/子文件夹中的每个文件执行此操作。

这必须是一个bat文件。以下是我到目前为止的情况:

@echo off
set RESULT_FILE="result.txt"
set /p "var1=Enter the String to Find: "
set /p "var2=Enter the String to Replace with: "

pushd %~p0
for /f "delims=" %%a in ('dir /B /S *.js') do (
  for /f "tokens=3 delims=:" %%c in ('find /i /c "%var1%" "%%a"') do (
    if %%c neq 0 (
        echo %var1%
    )
 )
) 

popd

这是返回找到的变量,我只是在努力解决它的问题。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

您可以在Windows上使用sed吗?

for /f "delims=" %%a in ('dir /B /S /A-D *.js') do sed -ibak "s/%var1%/%var2%/g" "%%~fa"
Usage: sed [OPTION]... {script-only-if-no-other-script} [input-file]...

  -n, --quiet, --silent
                 suppress automatic printing of pattern space
  -e script, --expression=script
                 add the script to the commands to be executed
  -f script-file, --file=script-file
                 add the contents of script-file to the commands to be executed
  -i[suffix], --in-place[=suffix]
                 edit files in place (makes backup if extension supplied)
  -l N, --line-length=N
                 specify the desired line-wrap length for the `l' command
  -r, --regexp-extended
                 use extended regular expressions in the script.
  -s, --separate
                 consider files as separate rather than as a single continuous
                 long stream.
  --text     switch to text mode
  -u, --unbuffered
                 load minimal amounts of data from the input files and flush
                 the output buffers more often
      --help     display this help and exit
  -V, --version  output version information and exit

If no -e, --expression, -f, or --file option is given, then the first
non-option argument is taken as the sed script to interpret.  All
remaining arguments are names of input files; if no input files are
specified, then the standard input is read.

答案 1 :(得分:1)

以下链接可能会有所帮助。建议的解决方案是使用替换的字符串创建一个新文件,并删除旧文件。

How to replace substrings in windows batch file

答案 2 :(得分:0)

使用fart,您可以在一行Windows bat脚本中执行您想要的操作。

fart.exe -r "C:\path\to\folder\*.*" string_to_be_replaced replace_string 

其中-r代表Process sub-folders recursively