55
votes
Accepted
How to compare a program's version in a shell script?
I don't know if it is beautiful, but it is working for every version format I know.
#!/bin/bash
currentver="$(gcc -dumpversion)"
requiredver="5.0.0"
if [ "$(printf '%s\n' &...
36
votes
Accepted
Bash - Integer expression expected
The test command, also named [, has separate operators for string comparisons and integer comparisons:
INTEGER1 -eq INTEGER2
INTEGER1 is equal to INTEGER2
vs
STRING1 = STRING2
the strings are equal
...
36
votes
How do I stop Bash from interpreting octal code instead of integer?
You can force conversion of a number to a specific base in bash like so:
$ foo=400
$ echo $((8#$foo))
256
$ bar=0100
$ echo $((10#$bar))
100
In general the format is $((base#value)).
32
votes
Accepted
How to increment the value of a (decimal) variable (with leading zero) by +1?
The leading 0 causes Bash to interpret the value as an octal value; 012 octal is 10 decimal, so you get 11.
To force the use of decimal, add 10# (as long as the number has no leading sign):
BN=10#$(...
23
votes
Accepted
Bash expansion hexadecimal
You can; you just need to break the range {0..F} into two separate ranges {0..9} and {A..F}:
$ printf '%s\n' {{0..9},{A..F}}{{0..9},{A..F}}
00
01
...
FE
EF
19
votes
Accepted
Extracting positive/negative floating-point numbers from a string
grep works well for this:
$ echo "2.5 test. test -50.8" | grep -Eo '[+-]?[0-9]+([.][0-9]+)?'
2.5
-50.8
How it works
-E
Use extended regex.
-o
Return only the matches, not the context
[+-]?[0-9]+([...
19
votes
Grep lines starting with 1, but not 10, 11, 100 etc
Sounds like you just want this:
$ grep '^1\b' a
1 TGCAG.....
1 TGCAG......
For the counting portion of this:
$ grep -c '^1\b' file
2

slm♦
- 366k
18
votes
How to increment the value of a (decimal) variable (with leading zero) by +1?
bash treats constants that start with 0 as octal numbers in its arithmetic expressions, so 011 is actually 9.
That's actually a POSIX requirement.
Some other shells like mksh or zsh ignore it (...
16
votes
Accepted
How can I numerically sort a single line of delimited items?
With gawk (GNU awk) for the asort() function:
gawk -v SEP='*' '{ i=0; split($0, arr, SEP); len=asort(arr);
while ( ++i<=len ){ printf("%s%s", i>1?SEP:"", arr[i]) };
...
16
votes
Accepted
Grep lines starting with 1, but not 10, 11, 100 etc
With awk:
awk '$1 == "1" { print; x++ } END { print x, "total matches" }' inputfile
16
votes
Accepted
How to sort lines by float number
If using GNU sort or compatible, you can use its -g switch to do a general numeric sort:
$ sort -g -k5,5 file
name: yyy --- time: 3.2 seconds
name: xxx --- time: 5.4 seconds
name: zzz --- time: 6.4 ...

slm♦
- 366k
16
votes
How to round to 2 decimals in bash like MS Excel does?
printf '%.2f\n' 8.125
Will convert that 8.125 textual representation of a decimal number to an internal binary representation using something like the standard strtod() or strtold() C functions, ...
15
votes
Bash expansion hexadecimal
Using printf:
$ printf '%.2x\n' {0..255}
The format string %.2x says to format the output as a zero-filled, two-digit, lower-case, hexadecimal number (%02x would have done the same).
If you want ...
15
votes
Accepted
bash + how to calculate percentage from number
bash cannot do floating point math, but you can fake it for things like this if you don't need a lot of precision:
$ number=248
$ echo $(( number*80/100 ))
198
15
votes
How to sort each 20 lines in a 1000 line file and save only the sorted line with highest value in each interval to another file?
Via awk:
NR%20==1 {max=$4 ; line=$0}
{ if ($4>max) {max=$4;line=$0} }
NR%20==0 {print line}
14
votes
How to compare a program's version in a shell script?
Shorter version, assuming GNU sort:
version_greater_equal()
{
printf '%s\n%s\n' "$2" "$1" | sort --check=quiet --version-sort
}
version_greater_equal "${gcc_version}"...
14
votes
Grep lines starting with 1, but not 10, 11, 100 etc
Either of these will pick out lines with a 1 in the first column
awk '$1 == 1'
grep -w '^1'
These can both can be extended so you don't even need the wc to count the lines
awk '$1==1 { x++ } END { ...
14
votes
How do I add numbers from two txt files with Bash?
Along the paste lines, but doing the math with bc:
$ paste -d+ file1 file2 | bc
7
9
11
13
15
The intermediate result (before bc):
$ paste -d+ file1 file2
1+6
2+7
3+8
4+9
5+10
For a more bash-...
14
votes
Accepted
Trim trailing zeroes off a number extracted by jq
Pass the price through tonumber:
curl -sS 'https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT' |
jq -r '.price | tonumber'
This would convert the price from a string to a number, removing ...
13
votes
How can I numerically sort a single line of delimited items?
Using perl there's an obvious version; split the data, sort it, join it back up again.
The delimiter needs to be listed twice (once in the split and once in the join)
eg for a ,
perl -lpi -e '$_=...
13
votes
Accepted
Convert a list of decimal values in a text file into hex format
You can do this using printf and bash:
printf '%08x\n' $(< test.txt)
Or using printf and bc...just...because?
printf '%08s\n' $(bc <<<"obase=16; $(< test.txt)")
In order to print ...
13
votes
Accepted
How to grep and cut numbers from a file and sum them
You can take help from paste to serialize the numbers in a format suitable for bc to do the addition:
% grep "30201" logfile.txt | cut -f6 -d "|"
650
1389
945
% grep "30201" logfile.txt | cut -f6 -d ...
12
votes
Reverse a hexadecimal number in bash
With fold + tac + tr :
$ echo 030201|fold -w2|tac|tr -d "\n"
010203
fold - split every 2 byte
tac - reverse cat
tr - remove newlines
12
votes
Accepted
How to generate a comma separated list of random ints
You can use paste -s to join lines:
shuf -i1-10 | paste -sd, -
This uses -i option of shuf to specify a range of positive integers.
The output of seq can be piped to shuf:
seq 10 | shuf | paste -sd, -...
12
votes
Accepted
How to round to 2 decimals in bash like MS Excel does?
If your system uses GNU coreutils then the numfmt command should be available, and allows you to choose between rounding ‘up’, ‘down’, ‘from-zero’ (the default), ‘towards-zero’, or ‘nearest’.
For ...
11
votes
Accepted
Simple bash script to print prime numbers from 1 to 1000
factor {2..1000} | awk 'NF==2{print $2}'
11
votes
Accepted
How to rank numbers in array by Unix?
If that list was in a file, one per line, I'd do something like:
sort -nu file |
awk 'NR == FNR {rank[$0] = NR; next}
{print rank[$0]}' - file
If it was in a zsh $array:
sorted=(${(nou)...
Only top scored, non community-wiki answers of a minimum length are eligible
Related Tags
numeric-data × 239text-processing × 88
awk × 84
shell-script × 37
linux × 27
bash × 25
sed × 25
grep × 20
sort × 20
shell × 13
command-line × 12
scripting × 12
regular-expression × 11
text-formatting × 8
test × 8
arithmetic × 8
printf × 7
floating-point × 7
columns × 6
bc × 6
variable × 5
csv × 5
random × 5
perl × 4
file-comparison × 4