[英]How to replace multiple lines from a text file using Powershell -replace
[英]How can i replace multiple lines in a text file using Powershell?
我有一個文件,我可以在文件中獲得 2 行。我有一個包含以下內容的文件。
public class Websites
{
//private const string URL = "https://au.yahoo.com/?p=us";
private const string URL = "https://www.google.com/";
//private const string URL = "https://stackoverflow.com/";
....
我可以像這樣單獨獲得 2 行:
$linegoogle = Get-Content "C:\myfile.cs" | Select-String "https://www.google.com/" | Select-Object -
ExpandProperty Line
$google = $linegoogle.Trim()
$linestackoverflow = Get-Content "C:\myfile.cs" | Select-String "https://stackoverflow.com/" |
Select-Object -ExpandProperty Line
$stackoverflow = $linestackoverflow.Trim()
但我要做的是以下幾點:
if (condition1)
{
//replace the 2 lines with
// private const string URL = "https://www.google.com/";
private const string URL = "https://stackoverflow.com/";
}
else if (condition 2)
{
//replace the 2 lines with
private const string URL = "https://www.google.com/";
// private const string URL = "https://stackoverflow.com/";
}
當然不是一個優雅的解決方案,但這可能適合你:
# set the condition here.
# can be either 'stackoverflow', 'google' or 'yahoo' as per your example file.
$condition = 'stackoverflow'
# read the file as single multiline string
$content = Get-Content "C:\myfile.cs" -Raw
# do the replacements depending on what is in $condition
$result = switch ($condition) {
'stackoverflow' {
$content -replace '(?m)^(\s+)(private const string URL = "https://www\.google\.com/.*";)', '$1//$2' -replace
'(?m)^(\s+)(private const string URL = "https://au\.yahoo\.com/.*";)', '$1//$2' -replace
'(?m)^(\s+)//(private const string URL = "https://stackoverflow\.com/.*";)', '$1$2'
}
'google' {
$content -replace '(?m)^(\s+)(private const string URL = "https://stackoverflow\.com/.*";)', '$1//$2' -replace
'(?m)^(\s+)(private const string URL = "https://au\.yahoo\.com/.*";)', '$1//$2' -replace
'(?m)^(\s+)//(private const string URL = "https://www\.google\.com/.*";)', '$1$2'
}
'yahoo' {
$content -replace '(?m)^(\s+)(private const string URL = "https://stackoverflow\.com/.*";)', '$1//$2' -replace
'(?m)^(\s+)(private const string URL = "https://www\.google\.com/*";)', '$1//$2' -replace
'(?m)^(\s+)//(private const string URL = "https://au\.yahoo\.com/.*";)', '$1$2'
}
}
# show the result on screen
$result
# write back to file
$result | Set-Content -Path "C:\myfile.cs"
請記住, -replace
使用正則表達式,因此您需要使用反斜杠對 url 中的特殊字符(在這種情況下,只有點)進行轉義。 還要在 url 中的最后一個斜杠后面附加.*
以說明任何可能的查詢字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.