如何根据文件名从多个 .txt 文件中提取字符串并将它们附加到 Powershell 上的新文件?
How to pull strings from multiple .txt files based on file name and append them to a new file on Powershell?
所以基本上我有一系列遵循相同命名法的 .txt 文件,例如:
1111210803_3CE_080977851__006908818__21110300013442021110420211105_20211110_120447_35418862_820
1111210933_3CE_006908818__2111040001442021110520211108_20211110_120447_35418860_820
这些所有文件的命名约定总是以日期开头,即111121
。在这些文件中,有几行字符串。我有兴趣从每个文件的第一行中提取一个特定的字符串。这是第一行的示例:
123456789012345678901234567890123 I 696969CCHKCTX 12345678901 DA 22758287
我尤其对 696969CCHKCTX
字符串感兴趣。所有文件都会有一些数字,后跟 CCHKCTX
值。我想从每个 .txt 文件中提取 696969CCHKCTX
字符串的 696969
部分并将它们全部附加到一个新文件中。
如果可能,我想对这些字符串求和并添加适当的小数位,因为它们实际上是美元值,即 696969
实际上代表 6969.69
和最后两个数字该字符串始终代表美分金额。此规则适用于所有 .txt 文件。我希望能够将此应用于同一日期的所有文件(即所有以 111121
开头的文件)
我该怎么做?
尝试以下结合了 Get-ChildItem
, Group-Object
, and ForEach-Object
, as well as the -replace
运算符的方法:
Get-ChildItem -File | # get files of interest; add path / filter as needed.
Group-Object { $_.Name.Substring(0, 6) } | # group by shared date prefix
ForEach-Object {
$firstLines = $_.Group | Get-Content -First 1 # get all 1st lines
# Extract the cents amounts and sum them.
$sumCents = 0.0
$firstLines.ForEach({
$sumCents += [double] ($_ -replace '.+\b(\d+)CCHKCTX\b.+', '')
})
# Output an object with the date prefix and the sum dollar amount.
[pscustomobject] @{
Date = $_.Name
Sum = $sumCents / 100
}
}
上面的代码向显示器输出了 table 格式的表示。您可以使用 >
/ Out-File
, for instance, though it's better to use a structured text format for later processing, such as Export-Csv
.
将其保存到文件中
所以基本上我有一系列遵循相同命名法的 .txt 文件,例如:
1111210803_3CE_080977851__006908818__21110300013442021110420211105_20211110_120447_35418862_820
1111210933_3CE_006908818__2111040001442021110520211108_20211110_120447_35418860_820
这些所有文件的命名约定总是以日期开头,即111121
。在这些文件中,有几行字符串。我有兴趣从每个文件的第一行中提取一个特定的字符串。这是第一行的示例:
123456789012345678901234567890123 I 696969CCHKCTX 12345678901 DA 22758287
我尤其对 696969CCHKCTX
字符串感兴趣。所有文件都会有一些数字,后跟 CCHKCTX
值。我想从每个 .txt 文件中提取 696969CCHKCTX
字符串的 696969
部分并将它们全部附加到一个新文件中。
如果可能,我想对这些字符串求和并添加适当的小数位,因为它们实际上是美元值,即 696969
实际上代表 6969.69
和最后两个数字该字符串始终代表美分金额。此规则适用于所有 .txt 文件。我希望能够将此应用于同一日期的所有文件(即所有以 111121
开头的文件)
我该怎么做?
尝试以下结合了 Get-ChildItem
, Group-Object
, and ForEach-Object
, as well as the -replace
运算符的方法:
Get-ChildItem -File | # get files of interest; add path / filter as needed.
Group-Object { $_.Name.Substring(0, 6) } | # group by shared date prefix
ForEach-Object {
$firstLines = $_.Group | Get-Content -First 1 # get all 1st lines
# Extract the cents amounts and sum them.
$sumCents = 0.0
$firstLines.ForEach({
$sumCents += [double] ($_ -replace '.+\b(\d+)CCHKCTX\b.+', '')
})
# Output an object with the date prefix and the sum dollar amount.
[pscustomobject] @{
Date = $_.Name
Sum = $sumCents / 100
}
}
上面的代码向显示器输出了 table 格式的表示。您可以使用 >
/ Out-File
, for instance, though it's better to use a structured text format for later processing, such as Export-Csv
.