我有一个这种格式的文本文件。
Configuration
;
; Authors: James
; Created: 10/11/2018
;
; Accepted
Name
James
Class
A2
Birthday
1 September 1982
Family Member
4
First Year Salary Number
100 USD
Second Year Salary Number
150 USD
Company Name
Unlimited Company
Total Salary Number
1300 USD
ExpectedSalaryNumber
FY:350 USD
SY:450 USD
TS:2000 USD
如果标题包含"Salary Number"
和"SalaryNumber"
,我想删除整个内容,还要删除标题"Configuration.... "
,并在删除后输出文件。我的期望输出文件是这样的
Name
James
Class
A2
Birthday
1 September 1982
Family Member
4
Company Name
Unlimited Company
我尝试了这个,但是它只是输出我删除的内容。 任何人都可以帮助我。 非常感谢。
$name = $false
& {
switch -regex -file .\Configuration.TXT {
'^*Salary Number*, ^*SalaryNumber*' { $name = $true; continue }
'^\s' { if ($name) { $_.Trim() }}
'^\S' { if ($name) { return } }
}
} | Remove-Item | Out-File .\Output.txt
ExpectedSalaryNumber
FY:350 USD
(White Space)
SY:450 USD
(White Space)
TS:2000 USD
答案 0 :(得分:1)
此示例仍然使用switch
,但是这次使用它来确定对每一行的处理方式,之后仅输出那些感兴趣的行(非薪水,非标题):
# These variables are changed to true if the line is a header or a salary
$header = $false
$salary = $false
Get-Content .\Configuration.TXT | ForEach-Object {
# The header flag is reset each time as the header checks are made first
$header = $false
# The $salary variable is only reset back to false when a new header is reached, provided it does not contain Salary\s*Number
# Use switch to find out what type of line it is
switch -regex ($_)
{
'^Configuration' # Beginning with Configuration
{
$header = $true
}
'^;' # Beginning with semicolon
{
$header = $true
}
# Data lines begin with a space
# move to the next line - do not alter $salary variable
'^\s'
{
continue
}
# If Salary Number is found set the flag
'Salary\s*Number' {
$salary = $true
}
# This is only reached once it has been determined the line is
# not a header
# not a salary header line
# not a data line
# i.e. only headers that are not Salary
# this resets the flag and makes lines eligible for output
default {
$salary = $false
}
}
# Only output lines that are not Salary and not headers
if ($salary -eq $false -and $header -eq $false) {
$_
}
} | Out-File .\Output.txt