基本上我有一條路徑
"root/main/EVILFOLDER/first/second/third/etc"
我想EVILFOLDER/專門洗掉路徑的第三段。問題是 EVILFOLDER 可以是任何東西,所以我不能只是硬編碼它,路徑長度和“/”的數量可以是任何不同的長度。
我有這個,它有效,但優雅它不是。
$path = "root/main/EVILFOLDER/first/second/third/etc"
$basePath = "{0}/{1}/" -f $path.Split('/')
$subFolder = "{3}/" -f $shortPath.Split('/')
$subFolderIndex = $shortPath.IndexOf($subFolder)
$newPath = $basePath $shortPath.Substring($subFolderIndex)
最終,我希望我可以將它寫成類似于“{0}/{1}/{3}...”的內容,以獲得路徑串列的其余部分。想法?
uj5u.com熱心網友回復:
試試這個:
'root/main/EVILFOLDER/first/second/third/etc',
'root/main/EVILFOLDEREVILFOLDEREVILFOLDER/first/',
'root/main/EVILFOLDEREVILFOLDEREVILFOLDER',
'root/main/zzz/first/second/third/etc',
'root/main/tinyEvil/aaaa/bbbb/cccc/dddd/eee' | ForEach-Object {
$good1, $good2, $notgood, $good3 = $_ -split '(?=/)',4
$newName = -join( $good1, $good2, $good3 )
[PSCustomObject]@{
OldName = $_
NewName = $newName
}
}
# Results
OldName NewName
------- -------
root/main/EVILFOLDER/first/second/third/etc root/main/first/second/third/etc
root/main/EVILFOLDEREVILFOLDEREVILFOLDER/first/ root/main/first/
root/main/EVILFOLDEREVILFOLDEREVILFOLDER root/main
root/main/zzz/first/second/third/etc root/main/first/second/third/etc
root/main/tinyEvil/aaaa/bbbb/cccc/dddd/eee root/main/aaaa/bbbb/cccc/dddd/eee
基本上我們關心保留$good1和$good2,它可能是也可能不是$good3之后,$notGood但這應該能夠處理它。
uj5u.com熱心網友回復:
$data = 'root/main/EVILFOLDER/first/second/third/etc' -split "/"; $data[0,1] $data[3..$data.length] -join "/"
uj5u.com熱心網友回復:
-split 很好,但這個正則運算式也應該可以解決問題:
$NewPath = $Path -replace "^([^/] /[^/] )/[^/] (.*)", '$1$2'
^ 字串的開頭
([^/] /[^/] )第一個塊保留在哪里[^/] 將保留任何字符(至少 1 個)但是/,因此這對應于“任何字符/任何字符”
/[^/] 要洗掉的字符(“/除/“之外的任何字符)
(.*) 要保留的第二個塊:“任何字符(可以沒有字符)”
替換為$1$2對應的塊以保留 1 和 2
如果您的路徑使用反斜杠,那么您需要在正則運算式中轉義它們: ^([^\\] \\[^\\] )\\[^\\] (.*)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/376418.html
