bash - 提取一组文件名中给定位置范围的唯一子字符串

标签 bash

我在给定的目录中有一组文件名(长度都相同),并且希望在文件名中的给定位置范围内找到所有不同子字符串(会有很多文件名具有相同的子字符串)。

具体来说,我感兴趣的子字符串从文件名的位置 7 开始,然后 10 个字符长

for file in *; do
      if [ -d "$file" ]; then
      file_basename=`basename $file`
      substr=${file_basename:7:10}
  done

我想将这些唯一的子字符串写入文件或数据结构,然后我可以循环遍历。

所以文件名集

........12s456tyer..........
........12s436tyer..........
........12s456tyer..........
........12s436tyer..........

会导致 2 个字符串

12s456tyer
12s436tyer

最佳答案

如果您使用 bash 4.0 或更高版本,您可以创建一个唯一的关联数组:

declare -A distinct_substrings=()
shopt -s nullglob # Prevent '*' from expanding to a literal '*'

for file in *; do
    if [[ -f $file ]]; then
        file_basename=${file##*/} # Not necessary if files are expanded from current dir.
        substr=${file_basename:7:10}
        distinct_substrings[$substr]=$substr
    fi
done

# Do stuff with "${distinct_substrings[@]}"

关于bash - 提取一组文件名中给定位置范围的唯一子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70628246/

相关文章:

arrays - 间接引用 bash 中的数组值

python - 在 bash 脚本中运行参数化的 python 脚本

bash - 文本替换 bash 脚本

bash - awk 或条件

linux - 在 bash 中使用变量复制命令

bash - 调试 tcl 流程 - 就像 bash -

linux - 需要将 getopts 与一个参数或另一个参数一起使用

regex - 如果该行不包含使用 sed 的另一个字符串,则将文本插入该行

node.js - 未找到自动前缀命令

linux - 如何在不解压缩的情况下列出 zip 存档中的文件?