在终端中将每个文件从 JPEG 转换为 GIF

Caz*_*azz 6 command-line convert

我之前使用 find 查找文件夹和子文件夹中的所有特定文件并对其进行处理

例如,我确实使用了

find /folder/ -name '*.txt' -exec chmod 666 {} \;
Run Code Online (Sandbox Code Playgroud)

此代码可轻松更改对文件夹中每个文本文件的写入权限。

现在我打算尝试以相同的方式将每个 jpg(甚至 JPG)转换为 gif,但不确定这是否那么容易。当我尝试使用 convert 命令工具时,它想要一个输入文件名和输出文件名,但我认为 find 没有给出,所以可能 find 不是正确的工具使用?

ter*_*don 8

Find 可以用于此,但我发现使用 shell 更容易。如果您的文件都在同一目录中(没有子目录),您可以这样做:

for f in /path/to/dir/*jpg /path/to/dir/*JPG; do
    convert "$f" "${f%.*}.gif"
done
Run Code Online (Sandbox Code Playgroud)

${var%something}语法将删除最短匹配的水珠something从可变的末端$var。例如:

$ var="foo.bar.baz"
$ echo "$var : ${var%.*}"
foo.bar.baz : foo.bar
Run Code Online (Sandbox Code Playgroud)

所以在这里,它是从文件名中删除最终扩展名。因此,"${f%.*}.gif"是原始文件名,但用.gif代替.jpg.JPG

如果确实需要递归到子目录中,可以使用 bash 的globstar选项(来自man bash):

globstar
    If set, the pattern ** used in a pathname expansion con?
    text will match all files and zero or  more  directories
    and  subdirectories.  If the pattern is followed by a /,
    only directories and subdirectories match.
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式启用它shopt -s globstar

shopt -s globstar
for f in /path/to/dir/**/*jpg /path/to/dir/**/*JPG; do
    convert "$f" "${f%.*}.gif"
done
Run Code Online (Sandbox Code Playgroud)


ste*_*ver 5

您确实可以将find- 与调用适当convert命令并使用参数替换生成输出文件的 shell 包装器一起使用。前任。

find . -name '*.jpg' -execdir sh -c '
  for f; do convert -verbose "$f" "${f%.*}.gif"; done
' find-sh {} +
Run Code Online (Sandbox Code Playgroud)

更改-name-iname包含.JPG扩展名(但请注意,.gif无论如何,替换扩展名都将是小写的)。