[英]Batch convert images files jpg, png to webp also in subfolders
I have found a script to convert files in a directoy but I need this with subdirectors 我已经找到一个脚本来在Directoy中转换文件,但是我需要使用子目录
Can you help me ? 你能帮助我吗 ?
#!/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
# cd to the directory of the image so we can work with just filenames
dir="$(dirname "$1")"
cd "$dir" || exit 1
base="$(basename "$1" .png)"
# create a WebP version of the PNG
cwebp -q 80 "$base".png -o "$base".webp
# delete the WebP file if it is equal size or larger than the original PNG
if [[ `stat -c '%s' "$base".webp` -ge `stat -c '%s' "$base".png` ]]; then
echo "Deleting WebP file that is no smaller than PNG"
rm -f "$base".webp
fi
# delete the WebP file if it is size 0
if [[ -f "$base".webp && ! -s "$base".webp ]]; then
echo "Deleting empty WebP file"
rm -f "$base".webp
fi
Good news: You won't be have to change the script! 好消息:您不必更改脚本!
you can find all directories inside the root dir by the command: 您可以通过以下命令在根目录下找到所有目录:
find /path/to/root/dir -type d
and you can add execute of some command for each found dir: 您可以为找到的每个目录添加一些命令的执行:
Assuming your script name is script.sh and it is located in your home dir, and you want to run it on all sub dirs under current dir (include the current dir): 假设您的脚本名称是script.sh,并且它位于主目录中,并且您想在当前目录(包括当前目录)下的所有子目录中运行它:
find . -type d -exec ~/script.sh "{}" \;
I had a similar issue when trying to find jpg images in a directory tree. 尝试在目录树中查找jpg图像时遇到类似的问题。 The tree
command helped me greatly. tree
命令极大地帮助了我。 Below is sample code I used to iterate through all directories and only function on those with jpg images. 以下是我用于遍历所有目录的示例代码,仅对具有jpg图像的目录起作用。
tree -dfi ${dir_name} | sed 's/$/\//g' | while read line
do
if [ `ls "${line}" | grep -ci jpg` -gt 0 ]
then
some code
fi
done
In your case you could grep for only PNG or perhaps do both jpg and png. 在您的情况下,您可以仅针对PNG进行grep转换,也可以同时进行jpg和png转换。 One other option would be find commands using the file name and output to a while loop 另一种选择是使用文件名查找命令并输出到while循环
find ${dir_name} -type f -name "*.jpg" | while read line
do
some code
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.