[英]How to use ls to list out files that end in numbers
我不确定我是否在bash中正确使用正则表达式。 我在使用bash shell的Centos系统上。 在我们的日志目录中,有附加数字的日志文件,即
stream.log
stream.log.1
stream.log.2
...
stream.log.nnn
不幸的是,还有一些具有新命名约定的日志文件,
stream.log.2014-02-14
stream.log.2014-02-13
我需要使用旧的日志文件命名格式来获取文件。 我找到了可行的方法,但我想知道是否还有另一种更优雅的方法可以做到这一点。
ls -v stream.log* | grep -v 2014
我不知道正则表达式如何在bash中工作和/或将什么命令(可能不是grep)用于管道输出。 我在想的cmd / regex是这样的:
ls -v stream.log(\.\d{0,2})+
毫不奇怪,这没有用。 也许我的逻辑是不正确的,但我想从名称为stream.log的cmdline列表文件中说,结尾处带有可选的.xyz,并在结尾处附加xyz = {1..999}。 请让我知道这是否可行,或者我提出的解决方案是否是执行此类操作的唯一方法。 在此先感谢您的帮助。
stream.log
的文件,没有附加任何数字,也需要将其添加到我的ls
清单中。 我尝试了注释和答案中的技巧,它们起作用了,但没有列出该文件。 您可以使用bash中的扩展模式匹配来做到这一点,例如
> shopt -s extglob
> ls *'.'+([0-9])
哪里
+(pattern-list)
Matches one or more occurrences of the given patterns
和其他有用的语法。
?(pattern-list)
Matches zero or one occurrence of the given patterns
*(pattern-list)
Matches zero or more occurrences of the given patterns
@(pattern-list)
Matches one of the given patterns
!(pattern-list)
Matches anything except one of the given patterns
或者,如果没有扩展的模式匹配,则可以使用一种不太简洁的解决方案
ls *'.'{1..1000} 2>dev/null
如果您有很多日志文件,请用更大的数字替换1000。 虽然我更喜欢grep选项而不是这个。
使用sed
的方法:
ls -v stream.log* | sed -nE '/log(\.[0-9]+)?$/p'
和一个使用egrep
:
ls -v stream.log* | egrep 'log(\.[0-9]+)?$'
这些打印出以“ log”结尾的行,并可选地以句点和任何正数位结尾的行之后。
您只需关注旧的日志文件格式中的破折号'-',就可以更加简单。 这是最低版本:
ls *-*
如果同一目录中有不同类型的日志文件,这可能会更安全一些:
ls stream.log.*-*
为了确保获得一个额外的文件,生成一个适合它的令人困惑的正则表达式没有意义-只需在ls行中包括它即可:
ls stream.log stream.log.*-*
请参阅@BroSlow的答案,这里是修复程序,其中还将包括stream.log。
shopt -s extglob
ls stream.log*(.)*([0-9])
stream.log stream.log.1 stream.log.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.