Unix Find 将文件名传递给 Exec 并在输出重定向中
Unix Find Passing Filename to Exec and In Output Redirect
我想对图像目录进行 base64 编码,删除 base64 输出中的换行符。然后我将其保存为 <imageName>.base64.txt
.
我可以使用以下 for
循环来做到这一点:
for file in $(find path/to/images -name "*.png"); do
base64 "$file" | tr -d "\n" > "$file".base64.txt
done
我如何用 find
使用 xargs
或 -exec
来做到这一点?
这与 How do I include a pipe |
in my linux find -exec command? 非常相似,但不包括您正在处理的案例。
要获取文件名,您可以运行一个-exec sh -c
循环
find path/to/images -name "*.png" -exec sh -c '
for file; do
base64 "$file" | tr -d "\n" > "${file}.base64.txt"
done' _ {} +
将 find -exec
与 +
一起使用可将 find
中的所有搜索结果一次性放入 sh -c '..'
中的小脚本中。 _
表示调用显式 shell 到 运行 在 '..'
中定义的脚本,其中收集的文件名列表作为参数。
使用 xargs
的替代版本与上面的循环在下面执行的一样昂贵。但是这个版本用 NUL
字符 -print0
分隔文件名并且 xargs
读回它在同一个字符上定界,两个 GNU 特定标志
find path/to/images -name "*.png" -print0 |
xargs -0 -I {} sh -c 'base64 {} | tr -d "\n" > {}.base64.txt'
我想对图像目录进行 base64 编码,删除 base64 输出中的换行符。然后我将其保存为 <imageName>.base64.txt
.
我可以使用以下 for
循环来做到这一点:
for file in $(find path/to/images -name "*.png"); do
base64 "$file" | tr -d "\n" > "$file".base64.txt
done
我如何用 find
使用 xargs
或 -exec
来做到这一点?
这与 How do I include a pipe |
in my linux find -exec command? 非常相似,但不包括您正在处理的案例。
要获取文件名,您可以运行一个-exec sh -c
循环
find path/to/images -name "*.png" -exec sh -c '
for file; do
base64 "$file" | tr -d "\n" > "${file}.base64.txt"
done' _ {} +
将 find -exec
与 +
一起使用可将 find
中的所有搜索结果一次性放入 sh -c '..'
中的小脚本中。 _
表示调用显式 shell 到 运行 在 '..'
中定义的脚本,其中收集的文件名列表作为参数。
使用 xargs
的替代版本与上面的循环在下面执行的一样昂贵。但是这个版本用 NUL
字符 -print0
分隔文件名并且 xargs
读回它在同一个字符上定界,两个 GNU 特定标志
find path/to/images -name "*.png" -print0 |
xargs -0 -I {} sh -c 'base64 {} | tr -d "\n" > {}.base64.txt'