循环浏览具有特定扩展名的所有文件并对其执行某些操作 [英] Looping through all files with specific extension and execute something on them

查看:83
本文介绍了循环浏览具有特定扩展名的所有文件并对其执行某些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用Linux Shell脚本的第一个小时,它看起来确实很强大,但是我仍然有些困惑.

This is my first hours with Linux shell script and it seems really powerful but i am still a little confused.

我想循环遍历目录中所有具有特定扩展名的文件递归(所有子目录,子子目录和...),并通过在它们上运行可执行文件来产生一个具有相同名称的新文件但是扩展名与原始文件的确切位置不同.

I want to loop through all the files with a specific extension in a directory recursively (all subdirectories, subsubdirectories and ...) and by running an executable on them produce a new file with same name but different extension on exact location of the original file.

以下是其伪代码:

files = list of all files (full path not just names) with extension .ext recursively

for file in files
    executable -option1 -option2 fullpath/file.ext1 > fullpath/file.ext2

推荐答案

  find . -name '*.ext1' -type f -exec sh -c \
    'executable -option1 -option2 ${0} > ${0%.ext1}.ext2' {} \;

查找是用于递归遍历文件树的标准工具.第一个参数(在本例中为.",表示当前工作目录)指定了开始下降的树的基础. -name 参数将搜索范围限制为与给定文件名匹配的文件. -type f 进一步将搜索限制为常规文件(与目录或其他实体相对). -exec 选项指示find在找到的每个与先前规范匹配的文件上执行指定的命令(名称以".ext1"结尾的常规文件),我们使用 sh 执行命令而不是直接调用可执行文件有两个原因:操作文件名很容易,并且甚至严格尝试使用 find 操作文件名也不是可移植的:必须给定与 {} 完全一样.

find is a standard tool for recursively walking a file tree. The first argument (in this case '.', meaning the current working directory) specifies the base of the tree at which to begin the descent. The -name argument limits the scope of the search to files that match the given filename. The -type f further limits the search to regular files (as opposed to directories or other entities). The -exec option instructs find to execute the specified command on every file it finds that matched the previous specifications (regular files whose name ends in ".ext1") We use sh to execute the command rather than directly calling the executable for 2 reasons: it is easy to manipulate the filename, and because it is not strictly portable to even try to manipulate the filename with find: it must be given exactly as {}.

$ {0%.ext1} 是使用文件名的shell语法( $ 0 的值是文件名,因为我们将其作为第一个参数传递给通过查找中的 {} 进行 sh ),并去除结尾的".ext1".我们在结果字符串后附加".ext2",以获取所需的输出文件.

The ${0%.ext1} is shell syntax that takes the filename (the value of $0 is the filename, since we pass it as the first argument to sh via {} in find) and strips off the trailing ".ext1". We append ".ext2" to that resulting string to get the desired output file.

这篇关于循环浏览具有特定扩展名的所有文件并对其执行某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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