[英]xargs/find/grep a list of files from a list of directories
I have a list of directories in a text file, wherein I want to find and change files that share a particular naming convention. 我在文本文件中有一个目录列表,我想在其中查找和更改共享特定命名约定的文件。
example file: 示例文件:
dir1
dir2
dir3
example folder structure with files 带有文件的示例文件夹结构
dir1/
thing.txt
thing.blah
dir2/
rar.txt
thing.blah
dir3/
apple.txt
another.text.file.txt
thing.blah
First, I find the name of the .txt, but then I want to perform a change on it. 首先,我找到了.txt的名称,但随后我想对其进行更改。 For example, i want to perform a sed command on thing.txt, rar.txt and apple.txt, but not another.text.file.txt.
例如,我想对thing.txt,rar.txt和apple.txt执行sed命令,而不是another.text.file.txt。
My question is, once I have all the file names, how do I perform a command on the files with those names? 我的问题是,一旦有了所有文件名,如何对具有这些文件名的文件执行命令? How can I then take those lines of text such as:
然后我该如何处理这些文本行,例如:
cat dirFile.txt | xargs ls | grep <expression>.txt
thing.txt
rar.txt
apple.txt
!cat | some command
and run an action on the actual files under the directories? 并在目录下的实际文件上执行操作?
What I'm getting is the above result, 我得到的是以上结果,
But what I need is 但是我需要的是
dir1/thing.txt
dir2/rar.txt
dir3/apple.txt
Say you have a file named dirs
which have all directories you need to search: 假设您有一个名为
dirs
的文件,其中包含您需要搜索的所有目录:
while IFS= read -r i; do
find "$i" -name '<expression>' -print0
done < dirs | xargs -0 some_command
If you know the directories doesn't have spaces or another type of separators you can simplify a bit: 如果您知道目录中没有空格或其他类型的分隔符,则可以简化一下:
find $(<dirs) -name '<expression>' -print0 | xargs -0 some_command
Perhaps your some_command
expect only one file at a time, in this case use -n1
: 也许您的
some_command
只期望一个文件,在这种情况下,请使用-n1
:
... | xargs -0 -n1 some_command
or move some_command
to find itself: 或移动
some_command
来查找自己:
find $(<dirs) -name '<expression>' -exec some_command {} \;
$(<dirs)
is a comand substitution . $(<dirs)
是命令替换 。 It reads the content (like cat
) of dirs
file and use it as the first arguments of find
. dirs
文件的内容(如cat
)并将其用作find
的第一个参数。 Empty dirs
is safe on GNU find (eg Linux) but you need at least one line - which is converted as one argument - on BSD (eg Mac OS X) dirs
是安全的,但是在BSD(例如Mac OS X)上,至少需要一行-它被转换为一个参数。 -print0
separates files with null
-print0
用null
分隔文件 -0
expects these null
chars. -0
需要这些null
字符。 -n1
says xargs
to send only one argument to some_command
-n1
说xargs
仅将一个参数发送给some_command
I guess my comments were not adequately expressed. 我想我的评论没有得到充分表达。 to get the output you desire;
获得您想要的输出;
cat dirfile.txt | xargs -I % find % -name <your file spec> or -regex <exp>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.