Windows bat脚本查找替换文件夹和子文件夹中的每个文件

标签 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

这将返回找到的变量,我正在努力寻找如何替换它。

在此先感谢您的帮助。

最佳答案

你能用sed吗?适用于 Windows?

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.

关于Windows bat脚本查找替换文件夹和子文件夹中的每个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17365333/

相关文章:

c++ - 如何混合两个音频 channel ?

c# - 在 C# 中获取文件和文件夹的透明外壳图标

java - 如何在java中等待并关闭命令提示符

javascript - javascript中以下正则表达式的含义是什么

javascript - 多个 HTML DOM - 解析和传输数据

c - 我们如何在命令行开发环境中编写程序?

c# - %~dp0 引用的批处理文件路径有时会在更改目录时更改的原因是什么?

batch-file - 用于重命名文件夹中的文件并再次命名的批处理文件

regex - 在终端中替换包含正则表达式的文本

linux - 无法运行在 Windows 上创建的 shell 脚本