This tag is meant for everything that has to do with mathematical operations. So if you want to ask a question about doing calculations in `awk`, or if you have a question about `bc`, this is the right tag to use.

learn more… | top users | synonyms

28
votes
10answers
39k views

Is there a way to get the min, max, median, and average of a list of numbers in a single command?

I have a list of numbers in a file, one per line. How can I get the minimum, maximum, median and average values? I want to use the results in a bash script. Although my immediate situation is for ...
16
votes
5answers
2k views

Parenthesis in bash arithmetic: 3 * (2 + 1)

expr does not seem to like parenthesis (used in mathematics to explicit operator priority): expr 3 * (2 + 1) bash: syntax error near unexpected token `(' How to express operator priority in bash?
15
votes
3answers
6k views

Bash: double equals vs -eq

I am doing integer comparison in bash (trying to see if the user is running as root), and I found two different ways of doing it: Double equals: if [ $UID == 0 ] then fi -eq if [ $UID -eq 0 ] ...
12
votes
7answers
14k views

How to compare to floating point number in a shell script

I want to compare two floating point numbers in a shell script. The following code is not working: #!/bin/bash min=12.45 val=10.35 if (( $val < $min )) ; then min=$val fi echo $min
11
votes
5answers
8k views

How to create a sequence with leading zeroes using brace expansion

When I use the following, I get a result as expected: $ echo {8..10} 8 9 10 How can I use this brace expansion in an easy way, to get the following output? $ echo {8..10} 08 09 10 I now that ...
9
votes
5answers
11k views

Binary to hexadecimal and decimal in a shell script

I have a context where I need to convert binary to hexadecimal and decimal and viceversa in a shell script. Can someone suggest me a tool for this?
9
votes
3answers
960 views

Why does “$(( ~33 ))” produce -34?

$ echo $(( 255 )) 255 $ echo $(( 33 )) 33 $ echo $(( ~33 )) -34 $ echo $(( ~255 )) -256 $ and my kernel is: $ uname -a Linux HOSTNAME 3.2.0-40-generic-pae #64-Ubuntu SMP Mon Mar 25 21:44:41 UTC ...
9
votes
1answer
245 views

Security Implications of using unsanitized data in Shell Arithmetic evaluation

In a comment to a recent question, Stéphane Chazelas mentions that there are security implications to double parentheses arithmetic such as: x=$((1-$x)) on most shells. My Google skills seem to be ...
8
votes
7answers
7k views

Doing simple math on the command line using bash functions: $1 divided by $2 (using bc perhaps)

Sometimes I need to divide one number by another. It would be great if I could just define a bash function for this. So far, I am forced to use expressions like echo 'scale=25;65320/670' | bc but ...
7
votes
4answers
5k views

creating a sequence of numbers, one per line in a file

Is there a way to create out of thin air, a file that is a sequence of numbers, starting at a given number, one per line? something like magic_command start 100 lines 5 > b.txt and then, b.txt ...
6
votes
2answers
701 views

Using bash “double paren” arithmetic expansion, math fails with leading zero

I have a simple script that deals with hours and minutes. If I want to calculate number of minutes since midnight having a string s hh:mm I tried splitting string then doing hh * 60 + mm My problem ...
6
votes
4answers
5k views

Check if $REPLY is in a range of numbers

I'm writing a shell script for Linux, using Bash, to translate any video-file into a MP4. For that, I'm using avconv with libvorbis for audio. Inside my script, I have a question for the user : ...
6
votes
3answers
136 views

Is it possible to use variables in count braces in Bash?

I'm searching for a solution to a Bash 4 problem I have. Bash 4 is able to iterate with leading zeros. For the line: for i in {001..005}; do echo -n $i" ";done;echo the output is 001 002 003 004 ...
6
votes
1answer
724 views

Why does a=0; let a++ return exit code 1?

Try it: $ a=0 $ let a++ $ echo $? 1 # Did the world just go mad? $ echo $a 1 # Yes, it did. $ let a++ $ echo $? 0 # We have normality. $ echo $a 2 Contrast with this: $ b=0 $ let b+=1 $ echo $? 0 ...
6
votes
1answer
307 views

What is the rationale for the bash shell not warning you of arithmetic overflow etc.?

There are limits set for the arithmetic evaluation capabilities of the bash shell. The manual is succinct about this aspect of shell arithmetic but states: Evaluation is done in fixed-width ...
5
votes
3answers
280 views

How to iterate a zero padded integer in bash?

How does one iterate a string with the form "[A-Z][0-9]*" Or for example: "A000001"? After receiving the variable I split: current_=$(mysql -h"$mysqlhost" -u"$mysqluser" -p"$PASS" "$DBNAME" -se ...
5
votes
3answers
2k views

how to suppress bash octal number interpretation? (to be interpreted as decimal)

I have this: date +"%H hours and %M minutes" I use festival to say it up.. but it says like: "zero nine hours".. I want it to say "nine hours"! but date always give me 09... so I wonder if bash ...
5
votes
2answers
281 views

Trying to do arithmetic in Perl rename tool (Debian)

Supposed I have five mp3 files: 01-trackfoo.mp3 02-trackbar.mp3 03-trackbaz.mp3 04-trackabc.mp3 05-trackxyz.mp3 Now I give a quick listen to the files (just mplayer on console will do the trick) ...
5
votes
1answer
477 views

Emacs simple arithmetics in query replace

Is it possible to do the following in emacs: Query replace all numbers in a region by the number +n, for example if you have: 12 and 7 are nice numbers let n be 3, then it should transform to 15 ...
5
votes
3answers
793 views

bash -e exits when let or expr evaluates to 0

I have a bash script that sets -e so the script will exit on any exit status != 0. I'm trying to do some basic shell arithmetic assigned to variables and sometimes the expression equals 0 which ...
4
votes
3answers
925 views

How do I create a bash script that sums any number of command line arguments?

How would I create a bash script that the user can use to sum any amount of command line arguments? For example, say my script is called sum: sum 3 3 sum 3 5 8 sum 9 8 21 38 And so on.. I ...
4
votes
2answers
5k views

Bash: integer expression expected, using read/test

I'm learning the basics of shell programming, so I wrote something simple like #!/bin/bash read var1 read var2 if [ var1 -lt var2 ]; then echo "var1 is lt var2" else echo "var2 is lt var1" fi ...
4
votes
2answers
2k views

Bash's conditional operator and assignment

Can we use bash's conditional operator with assignment operators after colon? Bash reference manual explains the arithmetic operators as follows. conditional operator expr ? expr : expr assignment ...
4
votes
1answer
2k views

awk high precision arithmetic

I am looking for a way to tell awk to do high-precision arithmetic in a substitution operation. This involves, reading a field from a file and substituting it with a 1% increment on that value. ...
4
votes
2answers
3k views

In bash, how to convert 8 bytes to an unsigned int (64bit LE)?

How can I 'read/interpret' 8 bytes as an unsigned int (Little Endian)? Perhaps there is a Bash-fu magic conversion for this? UPDATE: It seems that something got cross-wired in the interpretation of ...
4
votes
3answers
91 views

Arithmetic operations with expr and variables

Why won't this statement work? total=`expr $mPercent / 100 "*" .482 + $fPercent / 100 "*" .518` mPercent is a number as a result of an awk statement, as well as fPercent. I also get "expr: ...
4
votes
2answers
291 views

Redirect stderr of the double-parentheses construct

I'd like to be able to redirect the stderr of a double-parentheses construct. For example: a=$(($var/$var2)) would output some error messages if $var2 = 0, I do not want the user to see this. I ...
4
votes
2answers
39 views

How do I convert a string into a number interpreted in certain base in bash script?

I'm simply trying to convert a string $RECORD_HDR to a number $RECORD_SIZE, where echo $RECORD_HDR gives 003D and echo $RECORD_SIZE should give 61
3
votes
2answers
380 views

Why does $((40-35)) turn into 5?

What kind of strange shell syntax is hidden behind $((40-35)) and how come it calculates a value? Example: $> echo $((40-35)) 5
3
votes
4answers
136 views

Get pairs of lines and multiply [closed]

I'm trying to parse an html file for some values using bash. So I've got a big text file with numbers like this 3 2 4 2 What I want to do is get two lines, multiply both numbers and then store the ...
3
votes
3answers
253 views

Calculate and divide by total with AWK

Given the following data file... foo 10 bar 20 oof 50 rab 20 ... how would I print column two as a percent of the total of column two? In other words, I want... foo 10 10% ...
3
votes
2answers
247 views

Unit multiplier conversion in a shell script

I need to convert human-readable sizes into bytes. Unfortunately numfmt function is not accessible for me. Is there any other alternative? I need a shell/bash function to call from inside the sh ...
3
votes
2answers
867 views

Error when subtracting two negative numbers in ksh: “assignment requires lvalue”

I am trying to debug someone else's script: The code line is: y=$((${oldvalue[$x]}-${newvalue[$x]})) y gets calculated fine as long as both sides are positive numbers. However, I have a ...
3
votes
3answers
10k views

How to calculate values in a shell script?

I run this command in the terminal: grep "bla bla blah" blah* | echo "Blah: $(wc -l) / $(ls | wc -l) * 100" And I get this output: Blah: 44 / 89 * 100 What I expect to see: 49.4 Is there a ...
2
votes
4answers
3k views

Increment number in bash variable string

VERSION="4.0beta12" NEXT_VERSION=????? Writing an automatic release script, I have the current version in a variable $VERSION, and I would like to calculate the next version as $NEXT_VERSION. Rule: ...
2
votes
2answers
1k views

Comparison of decimal numbers in bash

My search this morning was about how could I compare two decimal numbers in bash, and I came to this answser: How to compare to floating point number in a shell script. This one, however, doesn't ...
2
votes
4answers
7k views

Calculate variable, and output it to another variable

The only calculator I know is bc. I want to add 1 to a variable, and output to another variable. I got the nextnum variable from counting string in a file: nextnum=`grep -o stringtocount ...
2
votes
2answers
930 views

Remove scientific notation bash script

When I convert MB to GB I'm getting below output. I want this output in normal format. When I use bc I'm getting an error. The text file contains nearly 100 such lines like this. I want to print this ...
2
votes
4answers
814 views

how to convert number to time format in shell script?

I want to cut a video into about 10 minute parts like this. ffmpeg -i video.mp4 -ss 00:00:00 -t 00:10:00 -c copy 01.mp4 ffmpeg -i video.mp4 -ss 00:10:00 -t 00:10:00 -c copy 02.mp4 ffmpeg -i video.mp4 ...
2
votes
4answers
309 views

Generate lists of page numbers for 2-up duplex printing: 2,3,… and 1,4,…

How can I generate the following increments? 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31,34,35,38,39,42,43,46,47,...,135 and ...
2
votes
3answers
83 views

Change value of a strings representing number

I have the following expression : a="2013" How can I change the value of a to "2012".
2
votes
2answers
2k views

How to divide a list of values by a number in command line?

I am trying to translate a simple program to the command line using unix utilities. For example, if I have a frequency list (after piping through uniq and sort) 5 x 4 y 1 z I want to print out, ...
2
votes
3answers
4k views

grepping a variable and adding 1 to it

I have a variable containing a leading zeroes number, and I want to grep this variable and that same variable plus one. I made several attempts but ran into errors. Here's what I want to do: read var ...
2
votes
1answer
180 views

Difference between two types of shell arithmetic

What is the difference between the following two shell arithmetic commands: echo $[ $var1 - 1 ] echo $(( $var1 - 1 )) Assuming var1 = 5 for example.
1
vote
2answers
11k views

How to add arithmetic variables in a script

I want to accumulate the line size of a number of files contained in a folder. I have written the following script: let a=0 let num=0 for i in folder/* do num=`cat $i | wc -l` ...
1
vote
4answers
639 views

Error: integer expression expected

I have written a script to determine the Load average on the server as follows: #!/bin/bash loadavg=`top -b -n1 | grep -i load | awk -F, '{print$4}'| awk -F: '{print $2}'` if [ "${loadavg}" -le 1 ...
1
vote
3answers
2k views

Shell scripting to divide numbers inside a file

I have a single column and 12 rows. Each row has numerical values. I want to divide each row values by some constant number (say C) using shell (bash) scripting. How to do this ? Thanks in advance..
1
vote
3answers
710 views

Writing a shell script to take output of an executable and perform some calculation

I am not much familiar with shell script. I want to write a shell script for the following pseudo-code: min=some garbage value for(i=1 to N){ // N and n will be taken as input for the shell script. ...
1
vote
3answers
100 views

Add or subtract a number from the names of all the files in a directory

I have a number of png and jpg files whose names are numbers, e.g.0100.png, in a directory, How can I add 1 to their names, for example, to get 0002.png and 0003.png from 0001.png and 0002.png ...
1
vote
1answer
1k views

Divide a variable by a number? [duplicate]

Basically I need to convert centimetres to inches which I am trying to do by diving the area in centimetres by 2.54. But I just cannot get this to work. echo "please enter width and then height" ...