我無法從文本檔案中重新組合某些檔案名(并丟棄其余檔案名)。檔案名被拆分(通常在三行)并且每個檔案名后總是有一個空行。我只想保留以OPENor開頭的檔案名FOUR。一個例子是:
OPEN.492820.EXTR
A.STANDARD.38383
333
FOUR.383838.282.
STAND.848484.NOR
MAL.3939
CLOSE.3480384.ST
ANDARD.39393939.
838383
我想要的輸出是:
OPEN.492820.EXTRA.STANDARD.38383333
FOUR.383838.282.STAND.848484.NORMAL.3939
感謝您的任何建議!
uj5u.com熱心網友回復:
一次讀取一行檔案并繼續連接它們直到遇到一個空行,此時輸出連接的字串并重復直到到達檔案末尾:
# this variable will keep track of the partial file names
$fileName = ''
# use a switch to read the file and process each line
switch -Regex -File ('path\to\file.txt') {
# when we see a blank line...
'^\s*$' {
# ... we output it if it starts with the right word
if($s -cmatch '^(OPEN|FOUR)'){ $fileName }
# and then start over
$fileName = ''
}
default {
# must be a non-blank line, concatenate it to the previous ones
$s = $_
}
}
# remember to check and output the last one
if($s -cmatch '^(OPEN|FOUR)'){
$fileName
}
uj5u.com熱心網友回復:
以下對我有用,您可以嘗試一下。
- 見https://regex101.com/r/AFRjgf/1的
Regex解釋。
$source = 'fullpath/to/inputfile.txt'
$destination = 'fullpath/to/resultfile.txt'
[regex]::Matches(
(Get-Content $source -Raw),
'(?msi)^(OPEN|FOUR).*?([\r\n\s] $|\z)'
).Value.ForEach({ -join($_ -split '\r?\n') }) |
Out-File $destination
用于檢測:
$txt = @'
OPEN.492820.EXTR
A.STANDARD.38383
333
FOUR.383838.282.
STAND.848484.NOR
MAL.3939
CLOSE.3480384.ST
ANDARD.39393939.
838383
OPEN.492820.EXTR
A.EXAMPLE123
FOUR.383838.282.
STAND.848484.123
ZXC
'@
[regex]::Matches($txt, '(?msi)^(OPEN|FOUR).*?([\r\n\s] $|\z)').Value.ForEach({
-join($_ -split '\r?\n')
})
輸出:
OPEN.492820.EXTRA.STANDARD.38383333
FOUR.383838.282.STAND.848484.NORMAL.3939
OPEN.492820.EXTRA.EXAMPLE123
FOUR.383838.282.STAND.848484.123ZXC
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/370374.html
