我正在尝试使用Powershell将一个基于多个字符串的文本文件拆分为两个文件。文件大小从5KB到15KB不等。
例如,文件数据的格式如下:
18600 - ABCD 2204 2020-04-11 00:00:00
18600 - ABCD 2204 2020-04-11 00:00:00
18600 - ABCD 2204 2020-04-11 00:00:00
18113 - ABCD 2204 2020-04-11 00:00:00
18113 - ABCD 2204 2020-04-11 00:00:00
19873 - ABCD 2204 2020-04-11 00:00:00
18764 - ABCD 2204 2020-04-11 00:00:00
19000 - ABCD 2204 2020-04-11 00:00:00
我需要将所有以18600、18113、19000等开头的行(或任何一组指定的5位数字)拆分为一个文件,将不以这些数字(否则)开头的所有剩余数据行拆分为另一个文件。
因此,逻辑是,对于文件中的每一行,如果它以这些指定数字集开头,则写到"file1“,否则写到"file2”。
$file = (Get-Content myfile.txt)
ForEach ($line in $file) {
If ($line -match a set of strings)
{
$newfile = all lines with set of beginning strings
}
Else {
$line | Out-File -Append different file
}
}我也对powershell之外的任何其他建议持开放态度。非常感谢你的帮助。
发布于 2020-07-11 01:25:52
假设您想要所有以18000..18999范围内的数字开头的行,这就完成了工作...笑一笑
它的作用是..。
constants
准备好对您的数据执行此操作时,请将整个代码块替换为对输入文件进行Get-Content.
[int]
18文件
<>F223>
这个代码..。
上发生的事情
代码..。
$SourceDir = "$env:TEMP\WBCha"
$TargetNumberRange = 18000..18999
$InFile = Join-Path -Path $SourceDir -ChildPath 'InFile.txt'
$18OutFile = Join-Path -Path $SourceDir -ChildPath '18_OutFile.txt'
$Not_18OutFile = Join-Path -Path $SourceDir -ChildPath 'Not_18OutFile.txt'
#region >>> create a file to work with
# when ready to do this for real, replace the whole "region" block with a Get-Contnet call
if (-not (Test-Path -LiteralPath $SourceDir))
{
$Null = New-Item -Path $SourceDir -ItemType 'Directory' -ErrorAction 'SilentlyContinue'
}
$HowManyLines = 1e1
$Content = foreach ($Line in 0..$HowManyLines)
{
$Prefix = @(18,19)[(Get-Random -InputObject @(0, 1))]
'{0}{1:d3} - {2}' -f $Prefix, $Line, [datetime]::Now.ToString('yyyyy-MM-dd HH:mm:ss:ffff')
}
$Content |
Set-Content -LiteralPath $InFile -ErrorAction 'SilentlyContinue'
#endregion >>> create a file to work with
foreach ($IF_Item in (Get-Content -LiteralPath $InFile))
{
if ([int]$IF_Item.Split(' ')[0] -in $TargetNumberRange)
{
Add-Content -LiteralPath $18OutFile -Value $IF_Item
}
else
{
Add-Content -LiteralPath $Not_18OutFile -Value $IF_Item
}
}18文件内容...
18000 - 02020-07-10 12:29:45:6736
18001 - 02020-07-10 12:29:45:6736
18004 - 02020-07-10 12:29:45:6746
18005 - 02020-07-10 12:29:45:6756
18006 - 02020-07-10 12:29:45:6756
18008 - 02020-07-10 12:29:45:6766
18010 - 02020-07-10 12:29:45:6766not 18文件内容...
19002 - 02020-07-10 12:29:45:6746
19003 - 02020-07-10 12:29:45:6746
19007 - 02020-07-10 12:29:45:6756
19009 - 02020-07-10 12:29:45:6766发布于 2020-07-11 01:24:34
假设您希望将以数字开头的行分隔到一个文件中,而将不以数字开头的行分隔到其他文件中,则可以使用-match操作符并传递一个正则表达式来扫描文本文件中的所有行,并分隔以数字开头的行。
代码片段如下所示:
$processText = $fileData.Split([Environment]::NewLine,[StringSplitOptions]::RemoveEmptyEntries)
{
if($row -match "\d") #Regex to check whether the first character of $row is a digit
{
$row | Out-File -FilePath "D:\DataStartingWithNum.text"
}
else
{
$row | Out-File -FilePath "D:\DataStartingWithText.text"
}
}如果您还有任何其他条件(您可能没有在上面的问题中解释),您可以使用类似的方法来过滤任何模式的初始数据,使用适当的正则表达式和-match运算符。
希望这能有所帮助。
https://stackoverflow.com/questions/62838860
复制相似问题