[英]Manipulate strings in a txt file with Powershell - Search for words in each line containing "." and save them in new txt file
[英]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
和ForEach-Object
以及-split
和-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] ((-split $_)[2] -replace '\D') })
# Output an object with the date prefix and the sum dollar amount.
[pscustomobject] @{
Date = $_.Name
Sum = $sumCents / 100
}
}
以上輸出一個表格格式的表示到顯示器。 例如,您可以使用>
/ Out-File
將其保存到文件中,但最好使用結構化文本格式進行后續處理,例如Export-Csv
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.