如何找到下一个可用的文件后缀(file_a.txt file_b.txt 等)

Nic*_*oul 6 shell-script filenames

每次发生特定事件时,我的系统都会创建一个新的文本文件。
文件应命名file_a.txt file_b.txt file_c.txt等。

在 Bash shell 脚本中,如何找出接下来应该使用的文件名?

例如,如果file_a.txt并且file_b.txt存在但不存在file_c.txt,那么下一个可用的文件名是file_c.txt.

如果它更容易,这可能是一个数字。
我开始设计算法,但可能有更简单的方法?

注意:文件每天都会被删除,因此到达的概率z为零。因此,在z任何策略都可以接受之后:aa使用整数,甚至使用 UUID。

PSk*_*cik 1

这是纯粹在 bash 中执行此操作的粗略方法(没有错误检查):

#helper function to convert a number to the corresponding character
chr() {
  [ "$1" -lt 256 ] || return 1
  printf "\\$(printf '%03o' "$1")"
}

#helper function to convert a character to the corresponding integer
ord() {
  LC_CTYPE=C printf '%d' "'$1"
}

#increment file
fn_incr(){

  #first split the argument into its constituent parts

  local fn prefix letter_and_suffix letter suffix next_letter
  fn=$1
  prefix=${fn%_*}
  letter_and_suffix=${fn#${prefix}_}
  letter=${letter_and_suffix%%.*}
  suffix=${letter_and_suffix#*.}

  #increment the letter part
  next_letter=$(chr $(($(ord "$letter") + 1)))

  #reassemble
  echo "${prefix}_${next_letter}.${suffix}"
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

fn_incr foo_bar_A.min.js
#=> foo_bar_B.min.js
Run Code Online (Sandbox Code Playgroud)

在 bash 中使用多字母索引执行此操作将需要更长的代码。您始终可以在不同的可执行文件中执行此操作,但是您可能希望批量增加文件名,否则可执行文件的启动开销可能会减慢您的程序的速度,令人无法接受。这一切都取决于您的用例。

在这里使用普通的旧整数可能是更好的选择,因为您不必手动管理 9++ 如何向左溢出。


chr()ord()无耻地从 Bash 脚本中窃取来获取字母表的 ASCII 值