regex - Linux:如何仅使用 ls 列出所有文件/目录

标签 regex linux bash grep ls

这是大学里的一道题。

问题是:列出 testfiles 文件夹中没有扩展名的所有文件/目录。
给出的正确答案是这样的:

ls testfiles | grep -v "\."

现在,为了理解 ls 正则表达式的工作原理,有人可以向我解释仅使用 ls 会怎样吗?此外,如果有任何示例也使用美元符号 $,以明确声明名称以 .[a-z] 结尾,我将不胜感激。

任何帮助,非常感谢。

还有一点!这个问题的另一个答案是使用:

ls testfiles | grep "^[^.]*$"

那是怎么读的?我这样读 ^[^.]*$:

^      -> does not contain
[^.]   -> starts with a dot
*      -> repeated zero or more times
$      -> till the end

我希望有人在这方面纠正我... 谢谢!

最佳答案

Unix 实用程序旨在用作过滤器,因此给出的答案很有意义,因为它最接近真实世界的应用程序。

不过,您确实明白,grep "\." 匹配带有“句点”(因此是扩展名)的所有内容,并且 grep -v "\."匹配其他所有内容(即补码)。

很难使命令比它已经存在的更精确,因为谁能说出什么是扩展,什么不是?


第 2 部分:ls 测试文件 | grep "^[^.]*$"

A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list; if the first character of the list is the caret ^ then it matches any character not in the list. For example, the regular expression [0123456789] matches any single digit.

http://unixhelp.ed.ac.uk/CGI/man-cgi?grep

所以 ^[^.]*$ 实际上意味着:

以一串字符开头和结尾的任何内容,其中每个字符都不是句点。

第一个插入符号不是否定,它的意思是开始于。第二个插入符号是“不”能指。

关于regex - Linux:如何仅使用 ls 列出所有文件/目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15605697/

相关文章:

linux - 在 Gnome Scheduler 中运行 Bash 脚本时出现奇怪的 Bash 错误

python - "‘python’ : No such file or directory"when running Python file as executable

Linux 库链接问题 - HADOOP HDFS C API

bash - cygwin 文件路径选项卡完成不起作用

string - Bash:如何在一行中应用两个字符串操作?

Ruby:具有默认值的 gets.chomp

php - 有趣的正则表达式

javascript - 字符串中的连续数字到数组

java - URL 中有效图像的正则表达式

javascript - RegExp 忽略 <code> 和 <pre> 标签之间的所有内容