我有一个文件,其中有多行由定界符“ |”分隔 在下面的示例中,我有5个“ |”定界符。因此,有6条消息。现在我要3条消息。
InputFile.txt
Line1
Line2
Line3
|
Line4
Line5
|
Line6
|
Line7
|
Line8
Line9
|
Line10
输出:
Line1
Line2
Line3
|
Line4
Line5
|
Line6
答案 0 :(得分:2)
只需在此处扔另一个选项即可
(Get-Content '.\InputFile.txt' -Raw).Split('|')[0..2] -join '|'
答案 1 :(得分:0)
使用Get-Content
获取文件的各行,并使用for循环逐行输出它们:
# Set the delimiter character and get the file contents
$delimiter = '|'
$content = Get-Content $filePath
# Loop over each line, set the delimiter count
$delimCount = 0
foreach( $line in $content ){
# If the line equals the delimiter and the delimiter count is 3, exit the loop
# ++$variable increments the variable by 1, then evaluates it
# The right side of an -and is not evaulated if the left side is $False
if( $line -eq $delimiter -and ++$delimCount -ge 3 ) {
break;
}
# Output the line
$line
}
答案 2 :(得分:0)
$groupcount = 0
Get-Content -Path '.\InputFile.txt' |
ForEach-object {
if ($_ -eq '|') {
$groupcount++
if ($groupcount -eq 3) { break }
}
if ($groupcount -lt 3) { Write-Output $_ }
}