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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4034896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:49:00  来源:igfitidea点击:

Find all files with a filename beginning with a specified string?

bashfind

提问by RikSaunderson

I have a directory with roughly 100000 files in it, and I want to perform some function on all files beginning with a specified string, which may match tens of thousands of files.

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

I have tried

我试过了

ls mystring*

but this returns with the bash error 'Too many arguments'. My next plan was to use

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

find ./mystring* -type f

but this has the same issue.

但这有同样的问题。

The code needs to look something like

代码需要看起来像

for FILE in `find ./mystring* -type f`
do
    #Some function on the file
done

回答by Sergio Tulentsev

use

find . -name 'mystring*'

回答by jacanterbury

ls | grep "^abc"  

will give you all files beginning(which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas findoperates recursively into sub folders.

将为您提供以 substring开头的所有文件(这是 OP 特别要求的)abc
它仅在当前目录上find运行,而递归地运行到子文件夹中。

To use findfor only files startingwith your string try

find仅用于以字符串开头的文件,请尝试

find . -name 'abc'*

找 。-名称'abc'*

回答by matson kepson

If you want to restrict your search only to files you should consider to use -type fin your search

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

try to use also -inamefor case-insensitive search

尝试也-iname用于不区分大小写的搜索

Example:

例子:

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


You could also perform some operations on results without pipe sign or xargs

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

Example:

例子:

Search for files and show their size in MB

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

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