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

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

我有以下文件夹结构:

1
2
3
4
5
6
├── longdirectorywithsillylengththatyouwouldntnormallyhave
│   ├── asdasdads9ads9asd9asd89asdh9asd9asdh9asd
│   └── sinlf
└── shrtdir
    ├── nowthisisalongfile0000000000000000000000000
    └── sfile

我需要找到文件和文件夹,它们的名称长度超过x个字符。我已经能够做到这一点:

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

1
2
3
longdirectorywithsillylengththatyouwouldntnormallyhave
asdasdads9ads9asd9asd89asdh9asd9asdh9asd
nowthisisalongfile0000000000000000000000000

但是,这只输出相关文件或文件夹的名称。如何输出这样的结果匹配的完整路径:

1
2
3
/home/user/Desktop/longdirectorywithsillylengththatyouwouldntnormallyhave
/home/user/Desktop/longdirectorywithsillylengththatyouwouldntnormallyhave/asdasdads9ads9asd9asd89asdh9asd9asdh9asd
/home/user/Desktop/shrtdir/nowthisisalongfile0000000000000000000000000

如果在文件上使用basename,则会丢失有关实际处理的文件的信息。

因此,必须更改regex才能识别最后一个路径组件的长度。

我能想到的最简单的方法是:

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

这利用了一个事实,即文件名不能包含斜杠。

因此,结果包含相对于您当前的cwd的路径,readlink可用于为您提供完整的路径。


1
2
find -name"????????????????????*"  -printf"$PWD/%P
"

找到的-printf选项非常强大。%P:

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

所以我们在前面加上$pwd/。

1
2
3
/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

为了防止我们手动计算问号,我们使用:

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


我现在不能测试它,但这应该可以做到:

1
find $(pwd) -exec basename '{}' ';' | egrep '^.{20,}$'