-2

这是一个文本示例,包括我试图用以下内容覆盖文件的符号:

Home        http://domain.tld
IP|http://domain.tld/path/1
Navbar, Top|http://domain.tld/
Tips/Tricks|#some text
Accordion 2|*more text
Text|=More Text

替换所有元字符,例如,

s!\t!symTA!g
s!\#!symHA!g

这是我的 Perl 代码:

`$ps New-Item $dir -Name $file -ItemType "file" -Force -Value "$out"`

但是,如果$out只有一行没有任何空格,它就可以工作!

但它大约有100行!

它给出了类似于以下的各种错误:

术语 BlogsymPIhttpsymCOLsymFSsymFSbislinks.comsymFSblog 不被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。在 line:2 char:1 + BlogsymPIhttpsymCOLsymFSsymFSbislinks.comsymFSblog

该文件已保存,但只有第一行(带有替换)。

4

2 回答 2

0

请注意,命令行字符串的最大长度约为 8k 个字符,因此这是一个糟糕的通用解决方案。更好的解决方案是将整个命令写入文件,然后将其作为脚本调用——我认为由于某种原因这是不可能的——否则你可能只使用 perl 来编写文件——或者使用 powershell 来执行工作。

我在草莓 perl 5.26.1.1 中对此进行了测试

use MIME::Base64 ();
use Encode qw/encode decode/;
use warnings;

$ps = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
$file = "c:\\strawberry\\test.txt";
$out = "Home        http://domain.tld
IP|http://domain.tld/path/1
Navbar, Top|http://domain.tld/
Tips/Tricks|#some text
Accordion 2|*more text
Text|=More Text";

$Command = "New-Item -path \"$file\" -ItemType file -Value @'\n$out\n'@";
$bytes = encode("UTF-16LE",$Command);
$encoded = MIME::Base64::encode($bytes);
$encoded =~ s/\R//g;
print "$ps -EncodedCommand $encoded";
$output = `$ps -EncodedCommand $encoded`;
print $output;

祝你好运!

于 2017-11-10T15:03:26.137 回答
-1

你为什么使用perl而不是直接PowerShell

ex.txt

Home        http://domain.tld
IP|http://domain.tld/path/1
Navbar, Top|http://domain.tld/
Tips/Tricks|#some text
Accordion 2|*more text
Text|=More Text

ex.ps1

(Get-Content -Path '.\ex.txt') -replace 'regex','desired value' |
    Set-Content -Path '.\ex.txt'

这将解析文档中的每一行并尝试将您的正则表达式匹配/替换为所需的。如果您不想污染原始文件,可以执行以下操作:

$Value = (Get-Content -Path '.\ex.txt') -replace 'regex','desired value'
New-Item -Path '.\pollute.txt' -Value $Value -ItemType 'File' -Force
于 2017-11-09T18:26:40.167 回答