Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum only few lines using bash from a file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading