如何使用 Windows 命令行环境查找和替换文件中的文本? [英] How can you find and replace text in a file using the Windows command-line environment?

查看:54
本文介绍了如何使用 Windows 命令行环境查找和替换文件中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Windows 命令行环境编写批处理文件脚本,并希望将文件中出现的某些文本(例如FOO")更改为另一个(例如BAR").最简单的方法是什么?有什么内置函数吗?

I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?

推荐答案

这里的很多答案帮助我指明了正确的方向,但没有一个适合我,所以我发布了我的解决方案.

A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.

我有 Windows 7,它内置了 PowerShell.这是我用来查找/替换文件中所有文本实例的脚本:

I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file:

powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"

解释一下:

  • powershell 启动 Windows 7 中包含的 powershell.exe
  • -Command "... " 是 powershell.exe 的命令行参数,包含要运行的命令
  • (gc myFile.txt) 读取 myFile.txt 的内容(gcGet-Content 命令)
  • -replace 'foo', 'bar' 只需运行替换命令将 foo 替换为 bar
  • <代码>|Out-File myFile.txt 将输出通过管道传输到文件 myFile.txt
  • -encoding ASCII 防止将输出文件转录为 unicode,正如注释所指出的
  • powershell starts up powershell.exe, which is included in Windows 7
  • -Command "... " is a command line arg for powershell.exe containing the command to run
  • (gc myFile.txt) reads the content of myFile.txt (gc is short for the Get-Content command)
  • -replace 'foo', 'bar' simply runs the replace command to replace foo with bar
  • | Out-File myFile.txt pipes the output to the file myFile.txt
  • -encoding ASCII prevents transcribing the output file to unicode, as the comments point out

Powershell.exe 应该已经是您的 PATH 语句的一部分,但如果不是,您可以添加它.它在我机器上的位置是 C:WINDOWSsystem32WindowsPowerShellv1.0

Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is C:WINDOWSsystem32WindowsPowerShellv1.0

更新
显然现代 Windows 系统内置了 PowerShell,允许您直接使用

Update
Apparently modern windows systems have PowerShell built in allowing you to access this directly using

(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt

这篇关于如何使用 Windows 命令行环境查找和替换文件中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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