使用批处理文件编辑文本文件 [英] Edit text file using batch file

查看:114
本文介绍了使用批处理文件编辑文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了上千个示例并进行了尝试,但实际上没有一个对我有用.我的要求很简单,我有一个文件-config.txt,它包含以下行之一:

I've searched a thousand of example and tried, but none of them actually works for me. My requirement is pretty straight forward, I have a file - config.txt, it has one of lines:

sqlServer = localhost

sqlServer=localhost

我正在尝试将此行更新为:

I'm trying to update this line to:

sqlServer = myMachine \ sql2012

sqlServer=myMachine\sql2012

我在线查看了一些示例,其中一些只是使用设置变量,或者有些不是替换而是插入.有一些示例正在写入一个新文件,但是新文件的每一行前面都有行号.我找不到如何编写批处理脚本的有用说明,并且没有更新文件批处理脚本适合我.

I looked examples online, some of them are just working with set variables, or some are not replacing but inserting. There are some examples are writing into a new file, but the new file has line number in front of each line. I don't find a useful instruction how to write batch scripts, and none of the update file batch scripts works for me.

如果您留下一些评论,将会非常有帮助.

It will be very helpful if you leave some comments.

预先感谢

推荐答案

已编辑-适应注释

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "config=.\config.txt"
    set "dbServer=localhost\sql2012"

    for /f "tokens=*" %%l in ('type "%config%"^&cd.^>"%config%"'
    ) do for /f "tokens=1 delims== " %%a in ("%%~l"
    ) do if /i "%%~a"=="sqlServer" (
        >>"%config%" echo(sqlServer=%dbServer%
    ) else (
        >>"%config%" echo(%%l
    )

    type "%config%"

    endlocal

逐行读取输入文件(for /f %%l),然后将每一行拆分(for /f %%a),如果该行中的第一个标记是"sqlserver",则替换该行,否则发送原始行归档.

Input file is read line by line (for /f %%l), then each line is split (for /f %%a) and if the first token in the line is "sqlserver" then the line is replaced, else the original line is sent to file.

用于在第一个for循环中检索信息的命令包括一个cd.>"%config%",它将删除文件的内容,因此最终的结果行(之前由for命令在内存中读取的行)删除它们)直接发送到同一文件.

The command used to retrieve the information in the first for loop includes an cd.>"%config%" that will remove the contents of the file, so the final resulting lines (that have been read in memory by the for command before removing them) are sent directly to the same file.

这篇关于使用批处理文件编辑文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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