Bash:选择随机图像后如何将文件名和目录名写入.txt文件

Bash:选择随机图像后如何将文件名和目录名写入.txt文件

我拼凑了一个 Bash 脚本来从多个子目录中随机选择一个图像,并且效果很好。

我现在需要两个 .txt 文件,其中包含图像名称和图像来自的目录名称。这两个txt文件的内容将被插入到Joomla网站上的一篇文章中。图像源是多个目录:/home/my-dir/public_html/images/archive-pics/

随机图像和两个 .txt 文件的目标目录是: /home/my-dir/public_html/images/archive-pic-of-day/

.txt 文件中所需的格式是:name.txt 文件中的“005.jpg”和 dir.txt 文件中的“outside-buildings”...不带引号。图片来源是....archive-pics/outside-building/005.jpg。

选择随机图像时,请对创建两个 .txt 文件所需的代码提出任何建议。我不是编码员,但我可以遵循说明。

我选择图像的脚本是:

#!/usr/bin/bash
#pic-of-day.sh: Randomly picks an image

#  /bin/bash /home/my-dir/pic-of-day.sh ...  for cron
# first, delete the existing image in the pic of the day folder
rm /home/my-dir/public_html/images/archive-pic-of-day/*.jpg

# now, look through the archive images and pick one to copy to the
# pic of the day folder
cp "$(find /home/my-dir/public_html/images/archive-pics/ -iname '*.jpg' \
        -print0 | shuf -z -n1)" \
    /home/my-dir/public_html/images/archive-pic-of-day/ 

谢谢你的评论@Pourko .....也许我没有解释得很好......

该图像通过文章容器显示在网站页面上,该文章容器将附带描述性文本样板。因为我们有多个包含图像的子目录,所以我想在样板中的适当位置插入文本来标识事件发生的位置。所有子目录都被标记为事件。一个简单的例子是:等等,等等......这个项目在[铁匠铺]进行了几年等等,等等。 [ ] 内的文本将是包含图像的子目录名称。我不需要整个路径,也不想要此时的文件名。故事本身将位于图像上方或下方。

为了使问题更加复杂,我必须使用 Joomla 扩展将内容导入到文章中,并且该扩展可以识别 .txt 文件。这就是为什么我认为两个包含数据的简单 .txt 文件会发挥作用。

现在,我不需要文件名,但我可以预见我们将来可能需要它。每天都会显示新图像和故事。抱歉,我不知道您的解决方案如何适用于我的文章。

答案1

您只需创建一个指向随机选择的文件的符号链接即可。这样您就不需要复制文件。

pic_dir='/home/my-dir/public_html/images/archive-pics'
link_dir='/home/my-dir/public_html/images/archive-pic-of-day'

rand_pic="$(find "$pic_dir/" -type f -iname '*.jpg' -print0 | shuf -z -n1)"
ln -sf "$rand_pic" "$link_dir/pic_of_the_day.jpg"

# to extract just the names, and save them in text files...
basename -- "$rand_pic" > "$link_dir/pic.txt"
basename -- "$(dirname -- "$rand_pic")" > "$link_dir/dir.txt"

相关内容