使用`find`命令与字符串替换结合使用。

huangapple go评论44阅读模式
英文:

use find command in conjunction with string replacement

问题

在bash中,可以在for循环中像这样做,以便系统地将目录中的pdf文件转换为png文件。

for file in $(ls .)
do
  convert ${file} ${file/.pdf/.png}
done

请注意,这里bash字符串替换语法允许编写简洁的代码。

当我尝试使用find时,我完全陷入了困境。是否有任何方法可以与(类似的)字符串替换语法一起在find中实现这个操作呢?当然,你可以像这样执行这个操作,例如:

find . | sed "s/\.pdf//" | xargs -i convert {}.pdf {}.png

但我喜欢能够使用(类似于bash的)字符串替换语法与find -exec一起使用的想法。

英文:

In bash, one can do something like this in a for loop to, say, convert pdf files in a directory to pngs systematically.

for file in $(ls .)
do
  convert ${file} ${file/.pdf/.png}
done

Note here that bash string replacement syntax allows for concise code.

When I tried the same with find I'm hopelessly stuck. Is there any way of implementing this with find in conjunction with (similar) string replacement syntax? Of course one can do this for example like this

find . | sed "s/\.pdf//" | xargs -i convert {}.pdf {}.png

but I like the idea of being able to use (something like bash) string replacement syntax together with find -exec

答案1

得分: 1

你需要运行Shell。

find . -maxdepth 1 -exec bash -c 'convert "$1" "${1/.pdf/.png}"' -- {} \;

为了提高可读性和正确性,你可以导出一个函数。

func() {
   convert "$1" "${1/.pdf/.png}"
}
export -f func
find . -maxdepth 1 -exec bash -c 'func "$@"' -- {} \;

最后,你可以使用xargs来并行执行工作流。

func() {
   convert "$1" "${1/.pdf/.png}"
}
export -f func
find . -maxdepth 1 -print0 | xargs -P$(nproc) -0n1 bash -c 'func "$@"' --

使用ShellCheck检查你的脚本。

英文:

You have to run the shell.

find . -maxdepth 1 -exec bash -c 'convert "$1" "${1/.pdf/.png}"' -- {} \;

You can export a function for readability and correctness.

func() {
   convert "$1" "${1/.pdf/.png}"
}
export -f func
find . -maxdepth 1 -exec bash -c 'func "$@"' -- {} \;

Finally, you can use xargs to parallelize workflow.

func() {
   convert "$1" "${1/.pdf/.png}"
}
export -f func
find . -maxdepth 1 -print0 | xargs -P$(nproc) -0n1 bash -c 'func "$@"' --

Check your script with shellcheck.

huangapple
  • 本文由 发表于 2023年5月29日 15:38:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76355472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定