Share via


Sum numbers in text file

Question

Sunday, December 17, 2017 4:24 PM

Hello,

I have a text file that looks like this:

12/17/2017 6:28:05 AM D:\Test\TM.txt       5     
12/17/2017 6:26:57 AM D:\Test\winpe8.iso 221,024
12/17/2017 6:26:57 AM D:\Test\file.doc      1,868

How can I sum the numbers at the end of each line without importing into Excel?

Thanks.

All replies (5)

Monday, December 18, 2017 6:26 PM âś…Answered

get-content input | foreach { -split $_ | select -index 4 } | measure -sum 

(luckily measure handles the commas in the numbers)


Sunday, December 17, 2017 4:38 PM

You could use Get-Content to get the content of the file. Then you could use a regular expression inside a foreach loop to get the numbers at the end of each line, but they are still "text" strings. So you convert them to numbers. Now you can simply build the sum of them.

If you're looking for something already written you can find scripts here: PowerShell Gallery or here: TechNet Gallery - resources for IT professionals.

Learn PowerShell: Microsoft Virtual Academy - Getting Started with Microsoft PowerShell.

Script requests: Microsoft Technet Script Center - Requests.

Best regards,

(79,108,97,102|%{[char]$_})-join''


Tuesday, December 19, 2017 5:28 AM

Thank you.

Russ


Wednesday, December 20, 2017 1:34 AM

Hi,

I'm checking how the issue is going, was your issue resolved?

And if the replies as above are helpful, we would appreciate you to mark them as answers, and if you resolve it using your own solution, please share your experience and solution here. It will be greatly helpful to others who have the same question.

Appreciate for your feedback.

Best Regards,
Albert

Please remember to mark the replies as an answers if they help.
If you have feedback for TechNet Subscriber Support, contact [email protected]


Thursday, December 21, 2017 1:09 PM

Please try like this as

$sum=0;get-content <text file path> | foreach {$sum=$sum + (-split $_ | select -index 4) };$sum

Make sure to vote or mark this as answer if you find this needful.

Have great day!!

Kam