我在给定的目录中有一组文件名(长度都相同),并且希望在文件名中的给定位置范围内找到所有不同子字符串(会有很多文件名具有相同的子字符串)。
具体来说,我感兴趣的子字符串从文件名的位置 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/