开发者

How to get "random" number based on a string in Bash?

I know there are plenty of random number generators out there, but I am looking for something that ma开发者_如何学Goy be a little more predictable. Is there a way to get a "random" number (one that would be the same in every instance) given a string? I would like to do this in bash. I am looking for something a little more advanced than the count of characters in the string, but not as advanced as a full checksum of it.

The end goal is to get a decimal value, so this could be ran against a string multiple times repeating the result.


You need a random number, but you don't want a full checksum, it's contradiction. I think md5sum and sha1sum is really easy to use and should fit your needs:

md5sum <<< "$your_str"

or

sha1sum <<< "$your_str"

Update:

If you need decimal numbers, just:

n=$(md5sum <<< "$your_str")
echo $((0x${n%% *}))


To hash the string abc to 3 decimals:

echo $((0x$(echo abc | md5sum | cut -f 1 -d " " | cut -c 1-3))) | cut -c 1-3

To get e.g. 4 decimals instead of 3, replace the two occurrences of 3 by 4:

echo $((0x$(echo abc | md5sum | cut -f 1 -d " " | cut -c 1-4))) | cut -c 1-4
  • $(echo abc | md5sum | cut -f 1 -d " " | cut -c 1-4) gives an hexadecimal of 4 digits.
  • $((0xHEX)) converts an hexadecimal (HEX) to decimal, which may have more than 4 digits even when HEX has 4 digits, e.g. ffff is 65535.
  • cut -c 1-4 gets the first 4 digits.


$ echo abc | md5sum | grep -Eo "[[:digit:]]{3}"  | head -n1
Result -> 248
$ echo xyz | md5sum | grep -Eo "[[:digit:]]{3}"  | head -n1
Result -> 627

Combined other answers!

For HEX colors

echo abc | sha1sum | grep -Eo "[a-f0-9]{6}"  | head -n1
03cfd7
echo abc | sha256sum | grep -Eo "[a-f0-9]{6}"  | head -n1
edeaaf
echo abc | sha512sum | grep -Eo "[a-f0-9]{6}"  | head -n1
4f285d
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜