Tag Info

Hot answers tagged

20

There is already a command for this: seq 100 104 will print these numbers on separate lines: 100 101 102 103 104 So just direct this output into a file: seq 100 104 > my_file.txt and seq 100 2 104 will print in increments of two, namely: 100, 102, 104


18

You can use the R programming language. Suppose the data is in a file named datafile: $ cat datafile 1 2 4 Invoke non-interactive R using Rscript: $ Rscript -e 'd<-scan("datafile", quiet=TRUE); \ cat(min(d), max(d), median(d), mean(d), sep="\n")' 1 4 2 2.333333 You can write an R script file: #! /usr/bin/env Rscript ...


15

From the bash man page: ((expression)) The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expres- sion is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let "expression". And further: ...


13

I have a handy bash function called calc: calc () { bc -l <<< "$@" } Example usage: $ calc 65320/670 97.49253731343283582089 $ calc 65320*670 43764400 You can change this to suit yourself. For example: divide() { bc -l <<< "$1/$2" } Note: <<< is a here string which is fed into the stdin of bc. You don't need to ...


11

I actually keep a little awk program around to give the sum, data count, minimum datum, maximum datum, mean and median of a single column of numeric data: #!/bin/sh sort -n | awk 'BEGIN{c=0;sum=0;}\ /^[^#]/{a[c++]=$1;sum+=$1;}\ END{ave=sum/c;\ if((c%2)==1){median=a[int(c/2)];}\ else{median=(a[c/2]+a[c/2-1])/2;}\ print ...


11

No need for bash, plain sh will do as well: #! /bin/sh - IFS=+; echo "$(($*))" $* in POSIX shells, expands to the list of positional parameters (in this case, the arguments to the script) separated by the first character of $IFS (or space if $IFS is unset or nothing if $IFS is empty). $((...)) is the shell internal arithmetic expansion operator (note ...


10

h=09; m=30;(( tot = 10#$h * 60 + 10#$m )); echo $tot The number before the # is the radix (or base) The number after the # must be valid for the radix The output is always decimal You can use a radix of 2 thru 64 (in GNU bash 4.1.5) As noted by enzoyib, the old alternative of $[expression] is depricated, so it is beter to use the POSIX compliant ...


10

Min, max and average are pretty easy to get with awk: % echo -e '6\n2\n4\n3\n1' | awk 'NR == 1 { max=$1; min=$1; sum=0 } { if ($1>max) max=$1; if ($1<min) min=$1; sum+=$1;} END {printf "Min: %d\tMax: %d\tAverage: %f\n", min, max, sum/NR}' Min: 1 Max: 6 Average: 3,200000 Calculating median is a bit more tricky, since you need to sort numbers ...


10

Bash does not understand floating point arithmetic. It treats numbers containing a decimal point as strings. Use awk or bc instead. #!/bin/bash min=12.45 val=10.35 if [ 1 -eq `echo "${val} < ${min}" | bc` ] then min=${val} fi echo $min If you intend to do a lot of math operations, it's probably better to rely on python or perl.


10

From help let: Exit Status: If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.. Since var++ is post-increment, I guess the last argument does evaluate to zero. Subtle... A perhaps clearer illustration: $ let x=-1 ; echo x=$x \$?=$? x=-1 $?=0 $ let x=0 ; echo x=$x \$?=$? x=0 $?=1 $ let x=1 ; echo x=$x \$?=$? x=1 $?=0 $ let x=2 ; echo ...


10

Prefix the first number with a 0 to force each term to have the same width. $ echo {08..10} 08 09 10 From the bash man page section on Brace Expansion: Supplied integers may be prefixed with 0 to force each term to have the same width. When either x or y begins with a zero, the shell attempts to force all generated terms to contain the same ...


10

The man page of bash says: ! ~ logical and bitwise negation Signed numbers are usually stored in Two's complement representation: ... -4 = 1100 -3 = 1101 -2 = 1110 -1 = 1111 0 = 0000 1 = 0001 2 = 0010 3 = 0011 ... This means if you take a number like 2 it is bitwise interpreted as 0010. After bitwise negation this becomes 1101, which is the ...


9

Actually you can set some attributes on variables using the declare (or the old typeset) builtin. declare -i var1 var2 will set integer attribute on those variables. After that assignments which attempt to set non-integer values to those variables will raise error. But your problem is with the syntax. When using a variable's value you have to prefix its ...


9

In your case, you can simply disable zero padding by append - after % in the format string of date: %-H By default, date pads numeric fields with zeroes. The following optional flags may follow '%': - (hyphen) do not pad the field _ (underscore) pad with spaces 0 (zero) pad with zeros ^ use upper case if possible # use opposite case if ...


8

Your arithmetic evaluation syntax is wrong. Use any of the following (the first is extremely portable but slow, the second is POSIX and portable except to the Bourne shell and earlier versions of the Almquist shell, the last three require ksh, bash or zsh): a=`expr "$a" + "$num"` a=$(($a+$num)) ((a=a+num)) let a=a+num ((a+=num)) Or you can just skip ...


8

It's fairly straightforward to do the conversion from binary in pure bash (printf is a builtin): Binary to decimal $ echo "$((2#101010101))" 341 Binary to hexadecimal $ printf '%x\n' "$((2#101010101))" 155 Going back to binary using bash alone is somewhat more complex, so I suggest you see the other answers for solutions to that.


8

So between 2^63 and 2^64-1, you get negative integers showing you how far off from ULONG_MAX you are. No. How do you figure that? By your own example, the max is: > max=$((2**63 - 1)); echo $max 9223372036854775807 If "overflow" meant "you get negative integers showing you how far off from ULONG_MAX you are", then if we add one to that, shouldn't ...


7

Linux ships with the seq command which does exactly that. If you don't have the seq command, it's an easy one-liner: i=100; while [ $i -le 104 ]; do echo $i; i=$((i+1)); done >b.txt or in ksh/bash/zsh for ((i=100; i<=104; i++)); do echo $i; done >b.txt or in zsh print -l {100..104} >b.txt


7

You can use package num-utils for simple manipulations... For more serious maths, see this link... It describes several options, eg. R / Rscript (GNU R statistical computation and graphics system) octave (mostly Matlab compatible) bc (The GNU bc arbitrary precision calculator language) An example of numprocess echo "123.456" | numprocess ...


7

The substring inside the ` ` must be a valid command itself: rownum=`echo $nextnum+1 | bc` But is preferable to use $( ) instead of ` `: rownum=$(echo $nextnum+1 | bc) But there is no need for bc, the shell is able to do integer arithmetic: rownum=$((nextnum+1)) Or even simpler in bash and ksh: ((rownum=nextnum+1))


7

A non-looping variant: { printf %d+ "$@"; echo 0; } | bc Example Put the above in a script file, sum. #!/bin/bash { printf %d+ "$@"; echo 0; } | bc Run it like so: $ ./sum 4 4 $ ./sum 4 4 5 13


6

Yes, it's possible, \& can be used in replace expression to represent the entire match, similarly \#& can be used to represent the entire match as number. More concretely: M-x query-replace-regexp \b[0-9]+\b RETURN \,(+ 3 \#&) And a quote from the documentation You can use Lisp expressions to calculate parts of the replacement string. To ...


6

$ echo 0.4970436865354813 | awk -v CONVFMT=%.17g '{gsub($1, $1*1.1)}; {print}' 0.54674805518902947 is probably the best you can achieve. Use bc instead for arbitrary precision. $ echo 'scale=1000; 0.4970436865354813 * 1.1' | bc .54674805518902943


6

If Perl is available: echo your_string | perl -ne ' BEGIN{ %suffixes=( K => 3, M => 6, G => 9, T => 12, P => 15, E => 18 ); $suffix_regex = join "|", keys %suffixes; } s/([0-9][0-9]*(?:\.[0-9]+)?)($suffix_regex)/$1e$suffixes{$2}/g; printf "%d\n", $_; ' Since this is to be used as a text filter, it's more ...


5

No need for anything but Bash: for version in 12.4alpha9 12.4alpha12 12.4alpha-2; do echo -n "$version => "; [[ "$version" =~ (.*[^0-9])([0-9]+)$ ]] && version="${BASH_REMATCH[1]}$((${BASH_REMATCH[2]} + 1))"; echo "$version"; done The only line really relevant to you, is the one with the regex check [[: it remembers everything ...


5

A leading zero on a numeric constant in shell arithmetic expressions denotes an octal constant. Here's a portable way of deleting initial zeros: h=${h#${h%%[!0]*}}; [ -n "$h" ] || h=0 In bash, ksh or zsh, you can explicitly specify base 10 with $((10#$h)).


5

Bash can do the math itself to some extent. It's not useful for accuracy, though, as it rounds. [user]$ echo "$(( 10/5 ))" 2 But you're exactly right - a bash function would be a simple shortcut and your example basically works. divide() { echo "scale=25;$1/$2" | bc } Throw that in your .bashrc and then you can: [user]$ divide 10 5 ...


5

If you're using the $xxx syntax, then the variable is expanded, and then the result is evaluated as an arithmetic expression. So, y=$((${oldvalue[$x]}-${newvalue[$x]})) Becomes y=$((-4144290000--4009685000)) and ksh complains about that unexpected -- operator. You can get around it by adding spaces as you found out, in which case it becomes: ...


5

To control the formatting of the output you can use printf either directly from awk or directly via the shell. However you can also control the output directly using du. For example you can specify -h to output the results in human readable formats. Examples $ du -h --max-depth=1 /home/saml/apps | tail -1 9.0G /home/saml/apps $ du -h --max-depth=1 ...


5

You could simply say: ((REPLY>=1 && REPLY<=32)) && REPLY=-2 ((REPLY>=33 && REPLY<=48)) && REPLY=-1 Quoting from the manual: ((...)) (( expression )) The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic). If the value of the expression is non-zero, the ...



Only top voted, non community-wiki answers of a minimum length are eligible