【发布时间】:2018-01-15 06:31:16
【问题描述】:
假设我有三个目录,每个目录中都有不同数量的文件(尽管在这个简化的例子中,它是四个):
BA-2016-05:
AG-1829A.jpg
AG-1829B.jpg
AG-1829C.jpg
AG-1830A.jpg
BA-2016-V01:
AG-1712A.jpg
AG-1712B.jpg
AG-1922A.jpg
AG-1922B.jpg
BA-2017-PD02:
AG-1100A.jpg
AG-1100B.jpg
AG-1100C.jpg
AG-1100D.jpg
我希望结果数组看起来像这样:
AG-1100A.jpg AG-1100B.jpg AG-1100C.jpg AG-1100D.jpg
AG-1712A.jpg AG-1712B.jpg
AG-1829A.jpg AG-1829B.jpg AG-1829C.jpg
AG-1830A.jpg
AG-1922A.jpg AG-1922B.jpg
数组将被保存到.txt 文档中,可以用空格或制表符分隔。
到目前为止,我已经稍微调整了 a response from elsewhere online 以按文件名升序列出所有排序的文件:
find ~/BA* -iname "*.jpg" |\
awk -vFS=/ -vOFS=/ '{ print $NF,$0 }' |\
sort -n -t / |\
cut -f2- -d/
使用filename="${fullpath##*/}" 切断路径的开头应该很容易,但在那之后我就卡住了。如何将此列表转换为上述格式的数组?
几点说明:
- 文件名的格式将始终为
AG-[numbers][A-D],或者为了更通用,为[letters][hyphen][numbers][A-D]。 - 扩展名将始终为
.jpg或.JPG,但适用于所有扩展名并将其保留在输出数组中的扩展名会加分。
编辑:我在下面包含了我正在使用的最终解决方案。它包括我得到的两个答案的混合内容,以及一些花哨的 awk 东西,然后输出用于更改制表符的空格。奇迹般有效。我还意识到我实际上需要包含一个 URL,该 URL 将通过将文件名/路径合并到其中来完成。但我很快就弄清楚了。无论如何,感谢大家的帮助,这是最终代码:
#!/bin/bash
# The number of the current line
current_nb=;
# Variable to store the current line before writing it
line=;
# Loop through all regular files of the directories and subdirectories specified
# Sort all file paths in ascending order (irrespective of the directory name)
for file in $(find ./BA* -iname "*.jpg" -printf '%f/%p\n' | sort -n -t / | cut -f2- -d/);
do
# Append image URL to each file in the loop
file_url=`sed 's/^.*\/\(.*\/.*\)/[INSERT URL HERE]/\1/' <<< "$file"`;
# Extract the number from the current file in the loop
nb=`sed 's/.*-\([0-9]\+\)[[:alpha:]].*/\1/' <<< "$file"`;
# For the first loop, when $current_nb is not initialized, we set $nb as the default value
current_nb=${current_nb:-$nb};
# If we stay on the same line...
if [ "$nb" -eq "$current_nb" ];
then
# ...then concatenate the new filename with the line currently being created
line="$line $file_url";
else
# Otherwise, append the line at the end of the output file (changing spaces to tabs)...
echo $line | awk -v OFS="\t" '$1=$1' >> url_list.txt;
# ...and prepare a new line
line="$file_url ";
current_nb=$nb;
fi;
done;
【问题讨论】: