我目前正在进行一项练习,要求我编写一个shell脚本,其功能是获取一个目录的命令行参数。该脚本获取给定目录,并查找该目录及其子目录中的所有.jpgs,并按修改时间的顺序创建所有.jpgs的图像条(最新的底部)。
到目前为止,我已写过:
#!bin/bash/
dir=$1 #the first argument given will be saved as the dir variable
#find all .jpgs in the given directory
#then ls is run for the .jpgs, with the date format %s (in seconds)
#sed lets the 'cut' process ignore the spaces in the columns
#fields 6 and 7 (the name and the time stamp) are then cut and sorted by modification date
#then, field 2 (the file name) is selected from that input
#Finally, the entire sorted output is saved in a .txt file
find "$dir" -name "*.jpg" -exec ls -l --time-style=+%s {} + | sed 's/ */ /g' | cut -d' ' -f6,7 | sort -n | cut -d' ' -f2 > jgps.txt
脚本按时间修改顺序正确输出目录的.jpgs。我目前正在努力的部分是如何将.txt文件中的列表提供给convert -append
命令,该命令将为我创建一个图像条(对于那些不知道该命令的人,输入的内容是:convert -append image1.jpg image2.jpg image3.jpg IMAGESTRIP.jpg
,其中IMAGESTRIP.jpg是由前3张图片组成的完整图像条文件的名称。
我无法弄清楚如何将.txt文件列表及其路径传递给此命令。我一直在搜索手册页以寻找可能的解决方案,但没有出现可行的解决方案。
答案 0 :(得分:2)
xargs
是你的朋友:
find "$dir" -name "*.jpg" -exec ls -l --time-style=+%s {} + | sed 's/ */ /g' | cut -d' ' -f6,7 | sort -n | cut -d' ' -f2 | xargs -I files convert -append files IMAGESTRIP.jpg
xargs的基本用法是:
find . -type f | xargs rm
也就是说,你为xargs指定一个命令,它会附加从标准输入接收的参数,然后执行它。 avobe线将执行:
rm file1 file2 ...
但是你还需要为命令指定一个最后一个参数,所以你需要使用xarg -I
参数,它告诉xargs你将使用的字符串来指示从标准输入读取的参数将在哪里放。
因此,我们使用字符串files
来表示它。然后我们编写命令,将字符串files
放在变量参数所在的位置,结果为:
xargs -I files convert -append files IMAGESTRIP.jpg
答案 1 :(得分:1)
将文件名列表放在名为filelist.txt
的文件中,并使用&符号前面的文件名调用convert
:
convert @filelist.txt -append result.jpg
这是一个小例子:
# Create three blocks of colour
convert xc:red[200x100] red.png
convert xc:lime[200x100] green.png
convert xc:blue[200x100] blue.png
# Put their names in a file called "filelist.txt"
echo "red.png green.png blue.png" > filelist.txt
# Tell ImageMagick to make a strip
convert @filelist.txt +append strip.png
因为总有一些图像在其名称中有一个讨厌的空间......
# Make the pesky one
convert -background black -pointsize 128 -fill white label:"Pesky" -resize x100 "image with pesky space.png"
# Whack it in the list for IM
echo "red.png green.png blue.png 'image with pesky space.png'" > filelist.txt
# IM do your stuff
convert @filelist.txt +append strip.png
顺便说一句,如果文件名中有空格,解析ls
的输出通常是不好的做法。如果要查找图像列表,跨目录并按时间排序,请查看以下内容:
# Find image files only - ignoring case, so "JPG", "jpg" both work
find . -type f -iname \*.jpg
# Now exec `stat` to get the file ages and quoted names
... -exec stat --format "%Y:%N {} \;
# Now sort that, and strip the times and colon at the start
... | sort -n | sed 's/^.*://'
# Put it all together
find . -type f -iname \*.jpg -exec stat --format "%Y:%N {} \; | sort -n | sed 's/^.*://'
现在,您可以将所有内容重定向到filelist.txt
并像这样调用convert
:
find ...as above... > file list.txt
convert @filelist +append strip.jpg
或者,如果你想避免使用中间文件并一次性完成,你可以在convert
从标准输入流中读取文件列表时制作这个怪物:
find ...as above... | sed 's/^.*://' | convert @- +append strip.jpg