shell 对关联数组中文件名的操作

x7rlezfr  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(95)

我的bash脚本使用一个关联数组来查找定义为文件名中第一个_之前的单词的模式,然后对其执行一些操作。

# the root directory of the script
output=$(pwd)
# the folder with input images
img=$output/!img

declare -A patterns
find_patterns() {
    for f in $img/*.png ; do
        pattern=${f%%_*}  # Remove everything after the first underscore.
        pattern_without_path=("${pattern[@]##*/}") # remove path from the pattern
        patterns[$pattern_without_path]=1 # add it to the array
    done
}

# see found patterns in the array
check_patterns() {
    for pat in "${!patterns[@]}"; do
        echo $pat
    done
}

问题是$pattern_without_path不适用于任何路径。例如,当其中一个文件夹包含_时,模式匹配文件夹名称,而不是图像名称。
如何自动删除包含已处理文件的脚本/输入文件夹的文件夹的任何位置的路径?

w9apscun

w9apscun1#

$pattern_without_path不适用于任何路径。例如,当一个子文件夹包含“_”时,模式被识别为文件夹名称,而不是图像的名称。
是的。您正在修剪第一个_字符处的整个路径。如果它出现在其中一个文件夹名称中,那么您将因此丢失有关路径中后续内容的任何信息。当你修剪掉剩下的文件夹时,你留下的是一个文件夹名的片段,而不是最终的文件名。
如何自动删除包含已处理文件的脚本/输入文件夹的文件夹的任何位置的路径?
若要避免包含_字符的文件夹路径出现问题,请先删除路径,* 然后 * 修剪_*尾部。
请注意,您的脚本引用不足,在这里.

pattern_without_path=("${pattern[@]##*/}")

.您将pattern_without_path的值设置为一个单元素数组,这似乎是一个错误(尽管可能不会导致实际故障)。此外,您将pattern视为其值是一个数组,而它不是。
这样会更好:

declare -A patterns
find_patterns() {
  for f in "$img"/*.png ; do
    image_basename="${f##*/}"
    patterns["${image_basename%%_*}"]=1
  done
}

相关问题