编写 bash 脚本以使用具有特定条件的数组检查目录中的文件名

Writing a bash script for checking filenames in a directory by using an array with specific conditions

有一个目录包含几个 XML 文件。

每个文件名的格式如下: yyyy-mm-dd-hh-mm-ss-AUFXXXXXXXXX.xml

一些 XML 文件名在 AUF 之后具有相同的编号,因为它们已被修改。 我想要一个 bash 脚本来识别这些类型的文件,通过检查时间戳保留原始文件并将修改后的文件移动到另一个文件夹。 我正在尝试编写 bash 脚本来解决这个问题。这是我到目前为止所得到的:

#!/bin/bash
declare -a filelist
shopt -s extglob

for file in $(ls -tr1 *AUF*); do
  filelist=(${filelist[@]} "$file")
  echo "${file}"
done

部分输出:

2019-11-14-17-44-04-AUF19000276.xml
2019-11-15-09-12-01-AUF19000276.xml
2019-11-15-09-27-26-AUF19000276.xml
2019-11-15-09-28-51-AUF19000276.xml
2019-11-18-13-50-34-AUF19000296.xml
2019-11-20-16-45-14-AUF19000300.xml
2019-11-27-12-16-25-AUF19000292.xml
2019-11-27-12-19-50-AUF19000225.xml
2019-11-27-17-11-04-AUF19000300.xml
2019-11-28-09-40-44-AUF19000294.xml
2019-11-29-17-03-33-AUF19000305.xml
2019-11-29-17-04-43-AUF19000306.xml
2019-11-29-17-05-41-AUF19000306.xml
2019-12-02-12-02-20-AUF19000305.xml
2019-12-02-12-03-00-AUF19000305.xml
2019-12-03-09-22-06-AUF19000307.xml
2019-12-04-10-49-03-AUF19000308.xml
2019-12-05-09-23-54-AUF19000310.xml
2019-12-05-09-24-41-AUF19000310.xml
2019-12-09-13-12-31-AUF19000256.xml
2019-12-09-13-59-42-AUF19000256.xml
2019-12-09-15-29-25-AUF19000281.xml
2019-12-09-15-30-13-AUF19000281.xml
2019-12-09-15-34-07-AUF19000284.xml
2019-12-09-15-39-39-AUF18000346.xml
2019-12-09-15-40-21-AUF19000058.xml
2019-12-10-16-19-35-AUF19000312.xml
2019-12-11-11-58-55-AUF19000313.xml

例如:我想保留第一个创建的文件 2019-11-14-17-44-04-AUF19000276.xml 并移动其他三个文件相同的号码到另一个目录。

我目前不知道如何通过数组检查并包含上述条件。 很高兴得到任何帮助!

我认为以下内容(减去 echo)可以完成工作...

# iterate over the AUF* parts
for i in $( ls | sed -r 's/^.*(AUF[^.]+)\.xml//' | sort -u )
# iterate over the sections, move all but the first (oldest) files
do for j in $( ls -1 *${i}*| tail -n +2 )
    do echo mv $j newdir
    done
done

如果输出看起来正常,请删除 echo =}

请您尝试以下操作:

dest="another"          # folder to store the modified files
mkdir -p "$dest"
declare -A seen         # associative array to count AUFXXX substring
while IFS= read -r f; do
    auf="${f##*-}"      # extract the substring after "AUF"
    auf="${auf%.*}"     # remove extension
    (( seen[$auf]++ )) && mv -- "$f" "$dest"
                        # if the AUFXXX substring is seen then move the file
done < <(find . -name "*AUF*.xml" -printf "%T@\t%p\n" | sort -n | cut -f 2-)

它从每个文件中提取 AUFXXX 子字符串,并在关联数组 seen 中统计出现次数。如果 seen 的值不为零,则该文件是修改后的文件并将其移动到另一个目录。