使用powershell在两行之间编辑文本

时间:2014-07-14 08:43:43

标签: powershell

我想更改此文字

PortNumber=10001
;UserName=xxxxxxxxx
;Password=xxxxxxxxx
CiPdfPath=xxxxx

进入这个

PortNumber=10001
UserName=xxxxxxxxx
Password=xxxxxxxxx
CiPdfPath=xxxxx

我不能简单地搜索;Username=xxxx;Password=xxxx,因为它们在文件中存在多次,需要在某些地方进行评论。

我找到了下一个命令

$file = Get-Content "Test.ini" -raw
$file -replace "(?m)^PortNumber=10001[\n\r]+;UserName=xxxx[\r\n]+;Password=xxxx","PortNumber=10001 `r`nUserName=xxxxx`r`nPassword=xxxxx"

它有效! 但也许它可以简化

4 个答案:

答案 0 :(得分:1)

如果你使用(?ms)(multiline-singleline)选项和here-strings,你可以用复制/粘贴完成大部分工作:

$string = 
@'
PortNumber=10001
;UserName=xxxxxxxxx
;Password=xxxxxxxxx
CiPdfPath=xxxxx
'@


$regex = 
@'
(?ms)PortNumber=10001
;UserName=xxxxxxxxx
;Password=xxxxxxxxx
CiPdfPath=xxxxx
'@

$replace = 
@'
PortNumber=10001
UserName=xxxxxxxxx
Password=xxxxxxxxx
CiPdfPath=xxxxx
'@

$string -replace $regex,$replace
PortNumber=10001
UserName=xxxxxxxxx
Password=xxxxxxxxx
CiPdfPath=xxxxx

答案 1 :(得分:0)

为什么不搜索您要替换的全文? 所以找到:

PortNumber=10001
;UserName=xxxxxxxxx
;Password=xxxxxxxxx
CiPdfPath=xxxxx

并替换为:

PortNumber=10001
UserName=xxxxxxxxx
Password=xxxxxxxxx
CiPdfPath=xxxxx

您可以使用正则表达式表达不相关的字符
http://www.regular-expressions.info/powershell.html http://www.powershelladmin.com/wiki/Powershell_regular_expressions

答案 2 :(得分:0)

您可以使用正则表达式。

甚至更简单,取决于您的要求;

如果您知道要替换的线条的亚麻布,您可以轻松地替换某些线条:

鉴于文件格式是您粘贴的文本(例如第2行的用户名和第3行的密码),请将文件读入行缓冲区。替换第2行和第3行,并将内容设置回文件。

$lines=(Get-Content .\Test.txt)
$lines[1]= $lines[1].Replace(";","")
$lines[2]= $lines[2].Replace(";","")
$lines|Set-Content .\Test.txt

答案 3 :(得分:0)

我可能会误解问题的本质,但你不是只是试图删除主要的分号吗?搜索exclusivley这些字符串是否很重要?

$file = Get-Content "Test.ini" -raw
$file -replace "(?sm)^;"
$file -replace "(?smi)^;(?=(username|password))"

两个示例都应该生成相同的输出。第一个将匹配所有领先的分号。如果使用前瞻用户名或密码,则第二个将匹配前导分号。

相关问题