【问题标题】:Find string in text file, replace data after string up until next comma character在文本文件中查找字符串,替换字符串后的数据直到下一个逗号字符
【发布时间】:2016-03-09 07:50:57
【问题描述】:

我有一个包含各种字符串的文本文件“info.txt”。 我想找到字符串 '"masterstring":' 的第一次出现 并将 '"masterstring":' 之后的所有内容替换为 "replacement data text" 但只到下一个逗号, 使用 .bat 脚本最快的方法是什么?

【问题讨论】:

  • 我的第一反应是看看 perl。你可以写一个正则表达式替换某些文本并且速度很快
  • 到目前为止您尝试过什么?你知道命令findfindstr,还有for /F吗?在命令提示符下键入命令后跟/? 以获取详细信息...
  • 一般情况下,你能想出什么。比如\"masterstring\":([^,]*),即匹配“masterstring”和一个冒号,然后将所有内容捕获到一个组中的逗号。有关工作演示,请参阅 this regex101 fiddle。但是,这看起来像是一些 json 文件,所以也许有更好的方法,例如解析和替换。
  • 感谢你们的帮助。不幸的是,在这种情况下,我只能使用 bat 或 vbs 文件来执行此操作。有什么想法吗?

标签: regex batch-file replace find


【解决方案1】:

您可以编写一个 .VBS 脚本来执行此操作,但改用 JScript 会更容易,因为 Batch 和 JScript 代码都可以合并到具有 .BAT 扩展名的同一个 hybrid 文件中。我复制了this post 的解决方案,并针对此请求稍作修改。

@set @a=0  /*
@cscript //nologo //E:JScript "%~F0" < input.txt > output.txt
@goto :EOF */

WScript.Stdout.Write(WScript.StdIn.ReadAll().replace(/masterstring.*,/,"masterstring replacement data text,"));

您还没有发布示例数据,所以我创建了一个简单的输入文件:

First line in data file.
First line with masterstring and data to be replaced, preserve text after comma.
Other line with masterstring and other data, that must not be changed.
Last line in file.

这是输出:

First line in data file.
First line with masterstring replacement data text, preserve text after comma.
Other line with masterstring and other data, that must not be changed.
Last line in file.

有关此方法的更多详细信息,请参阅上面的链接和该帖子中的链接。您也可以在此站点中搜索“jscript replace”和带有batch-file 标签的“jscript hybrid”。

【讨论】:

  • 谢谢。这是在正确的道路上,但我遇到了一些问题。我如何找到以下内容,包括引号:“masterstring”:“
  • 您应该使用 代码标签 来明确界定您的示例。是 "masterstring":" 还是 "masterstring": ?任何其他?请发布一个简短的输入示例以及基于此类输入的所需输出;否则这只是一个猜谜游戏......编辑你的问题(不要在 cmets 中发布数据)并使用代码标签!
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 1970-01-01
  • 2011-07-01
  • 1970-01-01
相关资源
最近更新 更多