这是大学里的一道题。
问题是:列出 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/