查找文件名以指定字符串开头的所有文件?

问题描述 投票:0回答:4

我有一个大约包含100000个文件的目录,我想对以指定字符串开头的所有文件执行一些功能,这可能会匹配数万个文件。

我已经尝试过了

ls mystring*

但这会返回 bash 错误“参数太多”。 我的下一个计划是使用

find ./mystring* -type f

但这也有同样的问题。

代码需要看起来像这样

for FILE in `find ./mystring* -type f`
do
    #Some function on the file
done
bash find
4个回答
429
投票

find
与通配符一起使用:

find . -name 'mystring*'

35
投票
ls | grep "^abc"  

将为您提供所有文件beginning(这是OP特别需要的)以及子字符串

abc

它仅在当前目录上运行,而
find
递归地运行到子文件夹中。

仅将

find
用于文件 starting 与您的字符串尝试

找到。 -名称“abc”*


8
投票

如果您只想将搜索限制为文件,您应该考虑在搜索中使用

-type f

尝试也使用

-iname
进行不区分大小写的搜索

示例:

find /path -iname 'yourstring*' -type f

您还可以在没有管道符号或 xargs 的情况下对结果执行一些操作

示例:

搜索文件并以 MB 为单位显示其大小

find /path -iname 'yourstring*' -type f -exec du -sm {} \;

0
投票
for file in mystring*; do
    some command "$file"   # …always double-quote expansions!
done

这是 Bash 陷阱 页面中的第一个主题。到目前为止,这里的所有其他答案都被解释为该页面中的陷阱。 这是指向此陷阱的直接链接。这是该页面的引用:

是的,如果您可以将 ls 或 find 的输出视为文件名列表并对其进行迭代,那就太好了。但你不能。整个方法存在致命缺陷,并且没有任何技巧可以使其发挥作用。您必须使用完全不同的方法。 这至少有6个问题:

If a filename contains whitespace (or any character in the current value of $IFS), it undergoes WordSplitting. Assuming we have a file named 01 - Don't Eat the Yellow Snow.mp3 in the current directory, the for loop will iterate over each word in the resulting file name: 01, -, Don't, Eat, etc.

If a filename contains glob characters, it undergoes filename expansion ("globbing"). If ls produces any output containing a * character, the word containing it will become recognized as a pattern and substituted with a list of all filenames that match it.

If the command substitution returns multiple filenames, there is no way to tell where the first one ends and the second one begins. Pathnames may contain any character except NUL. Yes, this includes newlines.

The ls utility may mangle filenames. Depending on which platform you're on, which arguments you used (or didn't use), and whether its standard output is pointing to a terminal or not, ls may randomly decide to replace certain characters in a filename with "?", or simply not print them at all. Never try to parse the output of ls. ls is just plain unnecessary. It's an external command whose output is intended specifically to be read by a human, not parsed by a script.

The CommandSubstitution strips all trailing newline characters from its output. That may seem desirable since ls adds a newline, but if the last filename in the list ends with a newline, `…` or $() will remove that one also.

In the ls examples, if the first filename starts with a hyphen, it may lead to pitfall #3. 
© www.soinside.com 2019 - 2024. All rights reserved.