从bash中的名称生成ID号
目前,我有一大堆与数字相关的名字,例如: 乔·布洛格斯-17从bash中的名称生成ID号,bash,random,Bash,Random,目前,我有一大堆与数字相关的名字,例如: 乔·布洛格斯-17 约翰·史密斯-23 保罗·史密斯-24 乔·布洛格斯-32 使用名称和数字,我想生成一个由4个数字组成的随机/唯一ID,它也以初始数字结尾 例如,Joe Bloggs和17会制作一些随机/独特的东西,比如:xxxx17 这在bash中可能吗?用其他语言会更好吗? 这将在基于debian和darwin的系统上使用。每个名称在添加编号后都会变得唯一,除非有两个Joe Bloggs 17。在你的例子中,有两个乔·布洛格斯,一个是17岁,另一
约翰·史密斯-23
保罗·史密斯-24
乔·布洛格斯-32 使用名称和数字,我想生成一个由4个数字组成的随机/唯一ID,它也以初始数字结尾 例如,Joe Bloggs和17会制作一些随机/独特的东西,比如:xxxx17 这在bash中可能吗?用其他语言会更好吗?
这将在基于debian和darwin的系统上使用。每个名称在添加编号后都会变得唯一,除非有两个Joe Bloggs 17。在你的例子中,有两个乔·布洛格斯,一个是17岁,另一个是32岁。把这些放在一起,你会发现“Joe Bloggs 17”和“Joe Bloggs 32”是不一样的。使用此方法,您可以简单地为每个名称+数字对分配一个数字,并在关联数组(字典)中记住该数字。不需要是随机的。当你发现字典中没有的名字时,只需不断增加数字,然后将新的数字与名字联系起来。如果独一无二是唯一的目标,那么对于10000人来说,你的状态很好
Python是一种很好的语言,但是您也可以在BASH中创建关联数组。对于一组10个字符长的名称,不可能确保4位以上的哈希(校验和)是唯一的 作为替代方案,您可以尝试
file="./somefile"
paste -d"\0\n" <(seq -f "%04g" 9999 | sort -R | head -$(grep -c '' "$file")) <(grep -oP '\d+' "$file")
所有行的格式均为RRRRXX
,其中:
是一个保证唯一的随机数(从RRRR
到0001
)9999
是您输入的数字XX
生成9999个4位数字(ofc,每个数字都是唯一的)seq
以随机顺序对行进行排序(基于它们的散列,因此得到唯一的随机数)sort-R
-从随机列表中仅显示前N行,其中N是文件中的行数head
- 行数由
计算(优于grep-c''
)wc-l
过滤文件中的数字grep-oP
- 最后,粘贴将两个输入合并到最终输出
使用由
生成的随机字符串,然后选择4位数字作为新ID中字符的第一位,您可以非常接近您想要做的事情。如果您想要更接近的ID,您可以从开头选择,或者从字符串的中间部分选择,以获得更多的随机性。在选择随机4之后,只需跟踪数组中使用的ID,并在分配每个新ID时对照数组进行检查。对于10000个左右的ID,此开销可以忽略不计:$(date+%N)
#!/bin/bash declare -a used4=0 # array to hold IDs you have assigned declare -i dupid=0 # a flag to prompt regeneration in case of a dup while read -r line || [ -n "$line" ]; do name=${line% -*} id2=${line##* } while [ $dupid -eq 0 ]; do ns=$(date +%N) # fill variable with nanoseconds fouri=${ns:4:4} # take 4 integers (mid 4 for better randomness) # test for duplicate (this is BASH only test - use loop if portability needed) [[ "$fouri" =~ "${used4[@]}" ]] && continue newid="${fouri}${id2}" # contatinate 4ints + orig 2 digit id used4+=( "$fouri" ) # add 4ints to used4 array dupid=1 done dupid=0 # reset flag printf "%s => %s\n" "$line" "$newid" done<"$1"
你们真的想要随机的,还是想要可复制的/确定性的?若你们的意思是散列,你们需要4个以上的数字才能使它唯一——多少是一堆?因为如果超过9999,则不能有唯一的4号ID.:)工作得很好!谢谢010817 161523 748024 269032
#!/bin/bash declare -a used4=0 # array to hold IDs you have assigned declare -i dupid=0 # a flag to prompt regeneration in case of a dup while read -r line || [ -n "$line" ]; do name=${line% -*} id2=${line##* } while [ $dupid -eq 0 ]; do ns=$(date +%N) # fill variable with nanoseconds fouri=${ns:4:4} # take 4 integers (mid 4 for better randomness) # test for duplicate (this is BASH only test - use loop if portability needed) [[ "$fouri" =~ "${used4[@]}" ]] && continue newid="${fouri}${id2}" # contatinate 4ints + orig 2 digit id used4+=( "$fouri" ) # add 4ints to used4 array dupid=1 done dupid=0 # reset flag printf "%s => %s\n" "$line" "$newid" done<"$1"
$ bash fourid.sh dat/nameid.dat Joe Bloggs - 17 => 762117 John Smith - 23 => 603623 Paul Smith - 24 => 210424 Joe Bloggs - 32 => 504732