码迷,mamicode.com
首页 > 系统相关 > 详细

powershell修改文件中某个字符串(-replace操作符)

时间:2018-02-10 18:53:29      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:file   size   替换   for   class   结果   参数   文件中   aaa   

使用-replace操作符

test.txt文件内容

1234
hello world
aaa "hhh"
fwdbz

test.ps1脚本文件

$(Get-Content E:\demo\test.txt) | 
Foreach-Object {$_ -replace ("1234","5678")} | 
Foreach-Object {$_ -replace ("hello world","hello java")} |
Out-File E:\demo\test.txt

这是个简单的字符串替换,将test.txt文件中的1234替换成5678,"hello world"替换成"hello java"

 

上面是无参数脚本执行,修改文件中字符串

下面这个是传递参数修改文件中字符串

test1.ps1脚本文件

#执行操作 test1.ps1  1234 5678参数之间通过空格隔开,操作结果如下将test.txt文件中的1234 替换为 5678

#输出参数1,2

Write-Host "$($args[0])"  "$($args[2])" 

$p1 = "$($args[0])"
$p2 = "$($args[1])"
$(Get-Content E:\demo\test.txt) |
Foreach-Object {$_ -replace ($p1,$p2)} |
Out-File E:\demo\test.txt

powershell修改文件中某个字符串(-replace操作符)

标签:file   size   替换   for   class   结果   参数   文件中   aaa   

原文地址:https://www.cnblogs.com/tracy123/p/8439347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!