我有十个文本文件(制表符分隔,20 万行)。我的意图是寻找字符 [, ], |并分别用 a、o、u 替换它们。任何提示如何使用 Windows 批处理脚本或 Powershell 执行此操作?
最佳答案
这应该会处理它,使用 Powershell。这可以通过直接 cmd.exe
来完成东西和一些内置的 Windows 可执行文件,但它会更丑陋,更难以理解。
它将读取某个文件,并在每一行中读取:
[
与 a
]
与 o
|
与 u
自
[
起需要转义符, ]
, 和 |
都是powershell中的特殊字符,反引号`
用于自动换行命令。$filename="textfile.txt"
$outputfile="$filename" + ".out"
Get-Content $filename | Foreach-object {
$_ -replace '\[', 'a' `
-replace '\]', 'o' `
-replace '\|', 'u'
} | Set-Content $outputfile
如果要处理文件列表,可以设置一个数组来执行此操作,并遍历该数组。
$filenames = @("/path/to/File1.txt", "file2.txt", "file3.txt")
foreach ($file in $filenames) {
$outfile = "$file" + ".out"
Get-Content $file | Foreach-object {
$_ -replace '\[', 'a' `
-replace '\]', 'o' `
-replace '\|', 'u'
} | Set-Content $outfile
}
关于Powershell 或批处理 : find and replace characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4126603/