如何将Linux查找、转换和复制命令合并为一个命令



我有以下cmd,它可以获取文件名中带有STP模式的所有.pdf文件,并将它们放入文件夹:

find /home/OurFiles/Images/ -name '*.pdf' |grep "STP*" | xargs cp -t /home/OurFiles/ImageConvert/STP/

我有另一个cmd,可以将pdf转换为jpg。

find /home/OurFiles/ImageConvert/STP/ -type f -name '*.pdf' -print0 |
while IFS= read -r -d '' file
do convert -verbose -density 500 -resize 800 "${file}" "${file%.*}.jpg"
done

有可能将这些命令合并为一个命令吗?此外,如果可能的话,我希望在单个命令中为转换后的图像文件名预挂一个前缀。示例:STP_OCTOBER.jpg到MSP-STP_OCTOPER.jpg。如有反馈,不胜感激。

find /home/OurFiles/Images/ -type f -name '*STP*.pdf' -exec sh -c '
destination=$1; shift        # get the first argument
for file do                  # loop over the remaining arguments
fname=${file##*/}          # get the filename part
cp "$file" "$destination" && 
convert -verbose -density 500 -resize 800 "$destination/$fname" "$destination/MSP-${fname%pdf}jpg"
done
' sh /home/OurFiles/ImageConvert/STP {} +

您可以将目标目录和找到的所有PDF传递给find-exec选项来执行一个小脚本
脚本删除第一个参数并将其保存到变量destination中,然后在给定的PDF路径上循环。对于每个文件路径,提取文件名,将文件复制到目标目录,如果复制操作成功,则运行convert命令。

也许类似于:

find /home/OurFiles/Images -type f -name 'STP*.pdf' -print0 |
while IFS= read -r -d '' file; do
destfile="/home/OurFiles/ImageConvert/STP/MSP-$(basename "$file" .pdf).jpg"
convert -verbose -density 500 -resize 800 "$file" "$destfile"
done

与您的两个单独命令相比,这个合并命令中唯一真正新的东西是使用basename(1)从文件名中删除目录和扩展名,以创建输出文件名。

最新更新