How to sum only few lines using bash from a file

Advertisements

How to sum only few lines from a file using bash

my file

10
20
30
40

I need to add only 10+30 using bash and output them to a variable
I have the code but its lengthy and doesnt look good

my code

a=$(sed -n '1p' file1)
b=$(sed -n '3p' file1)
total=`expr $a + $b`
echo $total

Is there any better way of doing it

>Solution :

With (POSIX):

awk 'NR==1{a=$1} NR==3{b=$1}END{print a + b}' file1
40

With :

read a b < <(sed -n '1p;3p' file1 | paste -sd' ' -)
echo $((a + b))
40

((...)) and $((...)) are arithmetic commands, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.

See http://mywiki.wooledge.org/ArithmeticExpression


Process Substitution >(command ...) or <(...) is replaced by a temporary filename. Writing or reading that file causes bytes to get piped to the command inside. Often used in combination with file redirection: cmd1 2> >(cmd2).
See http://mywiki.wooledge.org/ProcessSubstitution http://mywiki.wooledge.org/BashFAQ/024

Leave a ReplyCancel reply