用正则表达式替换的 Powershell 脚本不起作用
我有以下脚本,它逐行读取文件并用指定的文本替换每行中的模式,然后将其写入另一个文件:
param
(
[string] $inFilePath,
[string] $outFilePath,
[string] $inputPattern,
[string] $replacePattern
)
function Main()
{
$sr = $null;
$sw = $null;
try
{
$sr = New-Object System.IO.StreamReader($inFilePath);
$sw = New-Object System.IO.StreamWriter($outFilePath, $true);
do
{
$fileLine = $sr.ReadLine();
$fileLine2 = "";
if ($fileLine -eq $null)
{
break;
}
$fileLine = $fileLine + [System.Environment]::NewLine;
$fileLine2 = [System.Text.RegularExpressions.Regex]::Replace($fileLine, $inputPattern, $replacePattern);
$sw.Write($fileLine2);
}
while ($fileLine -ne $null);
}
finally
{
$sr.Dispose();
$sw.Dispose();
}
}
Main;
不幸的是,当我将脚本保存为 filereplace.ps1 并像这样调用它时
: >powershell .\filereplace.ps1 c:\docs\infile.txt c:\docs\outfile.txt '.{30,}\->.*\r\n' '*'
我明白了错误:
文件名、目录名或卷标语法不正确。
知道我可能做错了什么吗?我怀疑用于搜索替换的正则表达式模式有问题 - 当我删除 \->
时,它可以工作,但没有理由认为这应该是一个问题。
I have the following script which reads in a file line by line and replaces a pattern in each line with specified text, then writes this to another file:
param
(
[string] $inFilePath,
[string] $outFilePath,
[string] $inputPattern,
[string] $replacePattern
)
function Main()
{
$sr = $null;
$sw = $null;
try
{
$sr = New-Object System.IO.StreamReader($inFilePath);
$sw = New-Object System.IO.StreamWriter($outFilePath, $true);
do
{
$fileLine = $sr.ReadLine();
$fileLine2 = "";
if ($fileLine -eq $null)
{
break;
}
$fileLine = $fileLine + [System.Environment]::NewLine;
$fileLine2 = [System.Text.RegularExpressions.Regex]::Replace($fileLine, $inputPattern, $replacePattern);
$sw.Write($fileLine2);
}
while ($fileLine -ne $null);
}
finally
{
$sr.Dispose();
$sw.Dispose();
}
}
Main;
Unfortunately, when I save the script as filereplace.ps1 and call it like this:
powershell .\filereplace.ps1 c:\docs\infile.txt c:\docs\outfile.txt '.{30,}\->.*\r\n' '*'
I get this error:
The filename, directory name, or volume label syntax is incorrect.
Any idea what I might be doing wrong? I suspect there is something wrong with the regex pattern used in searching for a replacement - when I remove the \->
, it works, but there is no reason why this should be a problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正是重定向运算符
>
导致了命令行中的问题。用"
将整个命令括起来:It is the redirection operator
>
that causes the problem in the command line. Enclose the whole command with"
: