我需要Bash脚本在file.tag中生成自动标记。 当在同一天多次调用脚本时,必须增加COUNTER。当日期发生变化时,COUNTER必须重置为001.谢谢
我试过了
#!/bin/bash
touch file.tag
counter=0
date=$(date +"%y.%m.%d")
echo $date.$counter > file.tag
答案 0 :(得分:1)
试试这个:
class String
# Create a random String of given length, using given character set
#
# Character set is an Array which can contain Ranges, Arrays, Characters
#
# Examples
#
# String.random
# => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
#
# String.random(10)
# => "t8BIna341S"
#
# String.random(10, ['a'..'z'])
# => "nstpvixfri"
#
# String.random(10, ['0'..'9'] )
# => "0982541042"
#
# String.random(10, ['0'..'9','A'..'F'] )
# => "3EBF48AD3D"
#
# BASE64_CHAR_SET = ["A".."Z", "a".."z", "0".."9", '_', '-']
# String.random(10, BASE64_CHAR_SET)
# => "xM_1t3qcNn"
#
# SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
# BASE91_CHAR_SET = ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
# String.random(10, BASE91_CHAR_SET)
# => "S(Z]z,J{v;"
#
def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
Array.new(len){ chars.sample }.join
end
end
这个脚本:
如果日期不匹配,[[ ! -f ./file.tag ]] && touch file.tag
declare -i counter
dt=$(date +'%y.%m.%d')
counter=$(grep -c "${dt}" file.tag)
(( counter++ ))
printf '%s.%03d\n' ${dt} ${counter} >> file.tag
将返回0,从001
答案 1 :(得分:0)
我在你的例子中注意到file.tag总是只有一行:最后一个标签,对吗?
尝试使用此版本(使用shellcheck进行测试和检查):
#!/bin/bash
touch file.tag
date=$(date +"%y.%m.%d")
counter=0
if [ -s file.tag ]
then
lastline=$(tail -1 file.tag)
if [ "${date}" = "$(expr "${lastline}" : "^\([0-9.][0-9.]*\)[.][0-9][0-9]*$")" ]
then
counter=$(expr "${lastline}" : "^[0-9.][0-9.]*[.]\([0-9][0-9]*\)$")
counter=$((counter + 1))
fi
fi
printf "%s\n" "${date}.${counter}" > file.tag
脚本检查file.tag是否为空。
如果不为空,则从file.tag中提取最后一个日期,并将其与当前日期进行比较。
如果日期相等,那么它会从file.tag中提取计数器的最后一个值并递增它
最终用新标签
更新file.tag