Powershell从文本文件中删除一系列行

时间:2018-12-14 19:02:53

标签: powershell

我有一个包含此内容的文本文件

REV#           CUST REV#                                    
BARREL. ADD SLIDE TO CAST THE 1.03 & .413
DIAMETERS TO REV G                               
PART #   LED-4506-X  REF. JOB#  13445   
SHIP:  COLL    SHIP TO ADDRESS: SEE PO
QUESTIONER: NO  Penalty:  NO  QTY: 1
DUE DATE: 12/28/18       
P.O. TOTAL AMOUNT $1.00     TERMS: N/30
QUOTE: WRITTEN PULLED: YES 
HOURS:  100     MATERIAL: 1,000.00     RATE:    82
TYPE: DIDI   FOREMAN:    MP    SALESPERSON: RO      
DETAILS:   YES  / ENG     GANTT CHART:      YES    

我需要在SHIP

之后删除所有内容

我知道我可以使用这样的内容删除每行

(Get-Content C:\MyFile.txt) |
Where { $_ -notmatch "SHIP" } |
Where { $_ -notmatch "QUESTIONER:" } |
Where { $_ -notmatch "DUE DATE:" } |
Where { $_ -notmatch "P.O." }|
Where { $_ -notmatch "QUOTE:" }|
Where { $_ -notmatch "HOURS:" }|
Where { $_ -notmatch "TYPE:" }|
Where { $_ -notmatch "DETAILS:" }|
Set-Content C:\MyFile.txt

但是偶尔我会有随机的数据行,我需要删除并说这行

REV#           CUST REV#                                    
BARREL. ADD SLIDE TO CAST THE 1.03 & .413
DIAMETERS TO REV G                               
PART #   LED-4506-X  REF. JOB#  13445   
SHIP:  COLL    SHIP TO ADDRESS: SEE PO
QUESTIONER: NO  Penalty:  NO  QTY: 1
DUE DATE: 12/28/18,
12/29/18,
12/30/18         
P.O. TOTAL AMOUNT $1.00     TERMS: N/30
QUOTE: WRITTEN PULLED: YES 
HOURS:  100     MATERIAL: 1,000.00     RATE:    82
SOME OTHER INFORMATION
TYPE: DIDI   FOREMAN:    MP    SALESPERSON: RO      
DETAILS:   YES  / ENG     GANTT CHART:      YES   

上面的代码无法捕获到的其他日期或其他信息。如何从SHIP到文件末尾进行一系列的行操作?

2 个答案:

答案 0 :(得分:5)

尝试以下操作(假设您要覆盖文件,请确保备份C:\MyFile.txt

((Get-Content -Raw C:\MyFile.txt) -csplit '\r?\nSHIP:')[0] |
  Set-Content C:\MyFile.txt

这会完整读取您的文件Get-Content -Raw,然后将产生的多行字符串分割为-csplit(区分大小写),并以SHIP:开头的行

因此,所得数组的第一个元素([0])是文件的内容,直到但不包括SHIP:行。

答案 1 :(得分:0)

如果您想要的内容始终位于前4行,则可以执行以下操作:

(Get-Content C:\file.txt)[0..3] | set-content C:\outfile.txt