The other day, it was a one-liner addition tournament in a company chat, so I will leave it as a reminder.
Add the numbers 1-5 listed in the file below
$ cat num.txt
1
2
3
4
5
ShellScript
$ xargs < num.txt
1 2 3 4 5
$ xargs < num.txt | tr ' ' '+'
1+2+3+4+5
$ xargs < num.txt | tr ' ' '+' | bc
15
$ awk '{a=a+$0}END{print a}' < num.txt
15
$ S=0;while read N; do S=`expr "$N" "+" "$S"` ; done < num.txt ; echo $S
15
$ xargs < num.txt
1 2 3 4 5
$ xargs -n 1 < num.txt
1
2
3
4
5
$ xargs -n 1 seq < num.txt
1
1
2
1
2
3
1
2
3
4
1
2
3
4
5
$ xargs -n 1 seq < num.txt | wc -l
15
Perl
$ perl -nale 'for(@F[0]){$sum+=$_}END{print $sum}' num.txt
15
$ perl -nE '$sum+=$_;END{say $sum}' num.txt
15
PHP
$ php -R '$a=$a+$argn;echo $a;echo "\n";' < num.txt | tail -n 1
15
$ php -r "echo array_sum(file('num.txt'));"
15
Ruby
$ ruby -e 'puts ARGF.map(&:to_i).reduce(:+)' num.txt
15
$ ruby -ne 'BEGIN{$sum = 0}; $sum += $_.to_i; END{puts $sum}' num.txt
15
$ ruby -e 'p eval([*$<]* ".+")' num.txt
15
Python
$ python -c "import sys, operator;print reduce(operator.add, map(int, sys.stdin.readlines()))" < num.txt
15
$ python -c "print eval('+'.join(open('num.txt').read().split()))"
15
Recommended Posts