简体   繁体   中英

Powershell - Read a single text file and sort contents to multiple files based on text within the line

I'm looking for some direction on how to read a file line by line, then copy the line based on a search criteria to a newly created file. Since my description is probably poor, I've tried to illustrate below:

Single Text File Sample:
Name=N0060093G
Name=N0060093H
Name=N400205PW
Name=N400205PX
Name=N966O85Q0
Name=N966O85Q1

The script would read each line and use the "###" after "Name=N" , to create a new file name after the identifier, "###" to copy each appropriate line to the new file. So, lines "Name=N0060093G" and "Name=N0060093H" would go to " 006 .txt"; "Name=N400205PW" and "Name=N400205PX" would write to " 400 .txt", etc.

A RegEx style approach:

$File = 'test.txt'
Get-Content $File | ForEach {
    If ($_ -match '^Name\=N(?<filename>\d{3}).*') {
        $_ | Out-File -Append "$($Matches.Filename).txt" -WhatIf
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM