Advertisement
metalx1000

Adding Up a list of numbers with BASH

Aug 30th, 2023
1,780
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.51 KB | None | 0 0
  1. #create example file
  2. for i in {1..20};do echo $((1 + $RANDOM % 99));done > list.txt
  3.  
  4. #create example file, with floats
  5. for i in {1..20};do echo $((1 + $RANDOM % 99)).$((1 + $RANDOM % 99));done > list.txt
  6.  
  7. #add using bash
  8. echo $(($(cat list.txt|tr "\n" "+"|sed 's/+$/\n/g')))
  9.  
  10. #The above might cause issues with floats
  11. #it's better to use bc
  12. cat list.txt|tr "\n" "+"|sed 's/+$/\n/g'|bc
  13.  
  14. #you can also use paste
  15. paste -s -d+ list.txt|bc
  16.  
  17. #awk is another option
  18. cat list.txt| awk '{sum += $1} END {print sum}'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement