批处理脚本查找和替换文本文件中的字符串不存储修改后的文件创建一个额外的输出文件 [英] Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

查看:138
本文介绍了批处理脚本查找和替换文本文件中的字符串不存储修改后的文件创建一个额外的输出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写一个批处理脚本查找和替换文本文件中的字符串。下面是我的脚本。

 关闭@echo和放大器; SETLOCAL
设置搜索=%1
设置替换=%2
设置文本文件= INPUT.TXT
集的newfile = Output.txt的
(FOR / Fdelims =%% i的(%文本文件%)做(
    一套行= %%我
    SETLOCAL enabledelayedexpansion
    一套行=行:%搜索%=%替换%!
    回声(!行!
    ENDLOCAL
))>中%的newfile%
德尔%文本文件%
重命名%的newfile %%文本文件%

我能够成功替代词。

但我不想创建Output.txt的,然后将其重命名原始文件。

请帮我出了编辑一个文本文件,而不将其输出重定向到一个新文件..


解决方案

 关闭@echo
    SETLOCAL ENABLEEXTENSIONS disabledelayedexpansion    设置搜索=%1
    设置替换=%2    设置文本文件= INPUT.TXT    FOR / Fdelims =%% i的('键入%TEXTFILE%^&安培;打破^>中TEXTFILE%%')做(
        一套行= %%我
        SETLOCAL enabledelayedexpansion
        一套行=行:%搜索%=%替换%!
        >>!%TEXTFILE%回声(线!
        ENDLOCAL
    )

FOR / F 开始处理前将读取所有的数据。因此,在读取数据的过程中的文件被清空。那么所有的输出被附加到该文件。

I have written a batch script to find and replace a string in a text file. Following is my script.

@echo off &setlocal
set "search=%1"
set "replace=%2"
set "textfile=Input.txt"
set "newfile=Output.txt"
(for /f "delims=" %%i in (%textfile%) do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%newfile%"
del %textfile%
rename %newfile%  %textfile%

I am able to replace the word successfully.

But i dont want to create Output.txt and then rename it the original file..

Please help me out for editing a text file without redirecting the output to a new file..

解决方案

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        set "line=!line:%search%=%replace%!"
        >>"%textFile%" echo(!line!
        endlocal
    )

for /f will read all the data before starting to process it. So, in the process of reading the data the file is emptied. Then all the output is appended to the file.

这篇关于批处理脚本查找和替换文本文件中的字符串不存储修改后的文件创建一个额外的输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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