12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

いろんなスクリプトでワンライナー足し算

Last updated at Posted at 2014-08-12

先日会社のチャットでワンライナー足し算大会になったので覚え書き的に残します。

お題

以下のファイルに記載されている1 - 5の数字を足す

$ 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
$ cat num.txt | datamash sum 1
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
12
13
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?