我是最好的。页我很好。页我很搞笑。页
输出:
4我是最好的。页4我很好。页4我很有趣。页
PowerShell脚本需要在行开始时查找"页面"并添加" 4"。我创建了此脚本:
powershell -Command “sed ‘s/^Page/4 &/‘c:users*.txt >test.txt”
,但它在PowerShell中不起作用。
应该这样做:
$content = Get-Content "C:pathtomyfile.txt"
$newcontent = $null
Foreach($line in $content)
{
if($line -ne "")
{
$line = "4 "+"$line`r`n"
$newcontent += $line
}
else
{
$newcontent += "`r`n"
}
}
Set-Content -Path "C:pathtomyfile.txt" -Value $newcontent
powershell -command "foreach($ln in cat 'c:users*.txt'){if($ln -match 'page'){write-host '4'$ln}}"
或
powershell -command "foreach($ln in cat 'c:users*.txt'){if($ln -match 'page'){write-host '4'$ln}else{echo $ln}}"
取决于您是否只想输出其中的"页面"。
还请注意,PowerShell没有sed
的内置别名,并且您的/^Page/
在AnyCase中的行开始时只能匹配"页面"。
sed
是一个unix命令行工具,通常不会安装在Windows上(尽管有Windows端口)。
PowerShell做您要问的是
(Get-Content 'c:users*.txt') -replace '.*page','4$&' | Set-Content 'test.txt'
或(使用别名和重定向减少键入):
(cat 'c:users*.txt') -replace '.*page','4$&' > 'test.txt'
如果要分别更新每个文件(注意:不是您的UNIX代码代码段所做的),您会做这样的事情:
Get-ChildItem 'C:users*.txt' | ForEach-Object {
(Get-Content $_.FullName) -replace '.*page','4$&' | Set-Content $_.FullName
}
或(再次使用别名):
ls 'c:users*.txt' | %{(cat $_.FullName) -replace '.*page','4$&' | sc $_.FullName}
请注意,在这种情况下,您不能使用重定向,因为重定向操作员会在cat
读取它之前打开文件,这将有效地截断该文件。