Bash,在具有子目录的目录中的每个.jpg文件上运行脚本 [英] Bash, run script on every .jpg file in a directory with subdirectories

查看:39
本文介绍了Bash,在具有子目录的目录中的每个.jpg文件上运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些有效的代码,非常简单-它复制每个* .jpg文件,并将其重命名为* 1.jpg,不用担心.

I have some working code, it's very simple - it copies every *.jpg file, renames it into *1.jpg, no worries.

for i in *.jpg; do cp $i ${i%%.jpg}1.jpg;  done

我该如何运行它,以便它可用于目录中的每个文件,该目录的子目录中的每个文件

how can I run this, so that it works on every file in a directory, every file in the subdirectories of that directory

示例目录结构:

    test/test1/test2/somefile.jpg
    test/anotherfile.jpg
    test/test1/file.jpg
etc

推荐答案

对目录结构进行递归处理的命令是 find :

The command to do anything recursively to a directory structure is find:

find . -name "*.jpg" -exec bash -c 'file="{}"; cp "$file" "${file%%.jpg}1.jpg"' \;

在$ {find ...)中使用 -exec 代替i的将处理包含空格的文件名.当然,仍然有一个引用陷阱.如果文件名包含",则 file =" {}"将扩展为 file =" name包含引号字符"",显然已损坏( file 将成为包含引号的 name ,并将尝试执行 characters 命令).

Using -exec instead of for i in $(find ...) will handle filenames that contain a space. Of course, there is still one quoting gotcha; if the filename contains a ", the file="{}" will expand to file="name containing "quote characters"", which is obviously broken (file will become name containing quote and it will try to execute the characters command).

如果有这样的文件名,则可以使用 -print0 打印出用空字符(文件名中不允许的空字符)分隔的每个文件名,并在读取-d时使用$'\ 0'i 遍历以空分隔的结果:

If you have such filenames, or you might, then print out each filename separated with null characters (which are not allowed in filenames) using -print0, and use while read -d $'\0' i to loop over the null-delimited results:

find . -name "*.jpg" -print0 | \
    (while read -d $'\0' i; do cp "$i" "${i%%.jpg}1.jpg";  done)

对于任何类似这样的复杂命令,最好在不执行任何命令的情况下对其进行测试,以确保在运行该命令之前将其扩展为明智的命令.最好的方法是在实际命令前加上 echo ,因此,除了运行该命令外,您还将看到将运行的命令:

As with any complex command like this, it's a good idea to test it without executing anything to make sure it's expanding to something sensible before running it. The best way to do this is to prepend the actual command with echo, so instead of running it, you will see the commands that it will run:

find . -name "*.jpg" -print0 | \
    (while read -d $'\0' i; do echo cp "$i" "${i%%.jpg}1.jpg";  done)

一旦您察觉了一下并且结果看起来不错,请删除 echo 并再次运行以使其真实运行.

Once you've eyeballed it and the results looks good, remove the echo and run it again to run it for real.

这篇关于Bash,在具有子目录的目录中的每个.jpg文件上运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆