简体   繁体   English

Linux根据名称长度查找文件和文件夹,但输出完整路径

[英]Linux find files and folders based on name length but output full path

I have the following folder structure: 我具有以下文件夹结构:

├── longdirectorywithsillylengththatyouwouldntnormallyhave
│   ├── asdasdads9ads9asd9asd89asdh9asd9asdh9asd
│   └── sinlf
└── shrtdir
    ├── nowthisisalongfile0000000000000000000000000
    └── sfile

I need to find files and folders where their names length is longer is than x characters. 我需要查找名称长度大于x个字符的文件和文件夹。 I have been able to achieve this with: 我已经能够做到这一点:

find . -exec basename '{}' ';' | egrep '^.{20,}$'

longdirectorywithsillylengththatyouwouldntnormallyhave
asdasdads9ads9asd9asd89asdh9asd9asdh9asd
nowthisisalongfile0000000000000000000000000

However, This only outputs the name of the file or folder in question. 但是,这仅输出相关文件或文件夹的名称。 How can I output the full path of resulting matches like this: 我如何输出结果匹配的完整路径,如下所示:

/home/user/Desktop/longdirectorywithsillylengththatyouwouldntnormallyhave
/home/user/Desktop/longdirectorywithsillylengththatyouwouldntnormallyhave/asdasdads9ads9asd9asd89asdh9asd9asdh9asd
/home/user/Desktop/shrtdir/nowthisisalongfile0000000000000000000000000

If you use basename on your files, you lose the information about what file you are actually handling. 如果在文件上使用basename ,则会丢失有关实际处理的文件的信息。

Therefore you have to change your regex to be able to recognize the length of the last path component. 因此,您必须更改您的正则表达式才能识别最后一个路径组件的长度。

The simplest way I could think of, would be: 我能想到的最简单的方法是:

find . | egrep '[^/]{20,}$' | xargs readlink -f

This makes use of the fact, that filenames cannot contain slashes . 这利用了以下事实: 文件名不能包含斜杠

As the result then contains path relative to you current cwd , readlink to can be used to give you the full path. 结果是包含相对于您当前cwd路径, readlink 可以用来为您提供完整路径。

我现在无法测试,但这应该可以完成工作:

find $(pwd) -exec basename '{}' ';' | egrep '^.{20,}$'
find -name "????????????????????*"  -printf "$PWD/%P\n" 

The -printf option of find is very mighty. find的-printf选项非常强大。 %P: %P:

  %P     File's name with the name of the starting-point under which it was found removed. (%p starts with ./). 

So we add $PWD/ in front. 因此,我们在前面添加了$ PWD /。

/home/stefan/proj/mini/forum/tmp/Mo/shrtdir/nowthisisalongfile0000000000000000000000000
/home/stefan/proj/mini/forum/tmp/Mo/longdirectorywithsillylengththatyouwouldntnormallyhave
/home/stefan/proj/mini/forum/tmp/Mo/longdirectorywithsillylengththatyouwouldntnormallyhave/asdasdads9ads9asd9asd89asdh9asd9asdh9asd

To prevent us from manually counting question marks, we use: 为了防止我们手动计算问号,我们使用:

for i in {1..20}; do echo -n "?" ; done; echo
????????????????????

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM