Как заменить только часть строки с помощью PowerShell Get-Content -replace
У меня есть файл, в котором мне нужно изменить URL-адрес, не зная, что этот URL-адрес содержит, как в следующем примере: В файле file.txt я должен заменить URL-адрес, чтобы он был "https: // SomeDomain / Release / SomeText »или« https: // SomeDomain / Staging / SomeText »на« https: // SomeDomain / Deploy / SomeText ». Итак, все, что написано между SomeDomain и SomeText, следует заменить известной строкой. Есть ли какое-нибудь регулярное выражение, которое может помочь мне в этом?
Раньше я делал это с помощью следующей команды "
((Get-Content -path "file.txt" -Raw) -replace '"https://SomeDomain/Release/SomeText");','"https://SomeDomain/Staging/SomeText");') | Set-Content -Path "file.txt"
Это работает нормально, но я должен знать, содержит ли URL-адрес в файле file.txt Release или Staging перед выполнением команды.
Спасибо!
1 ответ
Вы можете сделать это с помощью регулярного выражения
-replace
, где вы захватываете части, которые хотите сохранить, и используете обратные ссылки для воссоздания новой строки
$fileName = 'Path\To\The\File.txt'
$newText = 'BLAHBLAH'
# read the file as single multilined string
(Get-Content -Path $fileName -Raw) -replace '(https?://\w+/)[^/]+(/.*)', "`$1$newText`$2" | Set-Content -Path $fileName
Детали регулярного выражения:
( Match the regular expression below and capture its match into backreference number 1
http Match the characters “http” literally
s Match the character “s” literally
? Between zero and one times, as many times as possible, giving back as needed (greedy)
:// Match the characters “://” literally
\w Match a single character that is a “word character” (letters, digits, etc.)
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
/ Match the character “/” literally
)
[^/] Match any character that is NOT a “/”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
( Match the regular expression below and capture its match into backreference number 2
/ Match the character “/” literally
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)