Linux 如何按最后的最新修改日期按时间顺序对“grep -l”的输出进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11392526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:45:10  来源:igfitidea点击:

How to sort the output of "grep -l" chronologically by newest modification date last?

linuxunixgrep

提问by Pyderman

I'm using the -l flag with grep to just print the matching file names.

我在 grep 中使用 -l 标志来打印匹配的文件名。

I want to then list the results (files) in ascending order i.e. newest last.

我想然后按升序列出结果(文件),即最新的最后。

Obviously

明显地

grep -l <pattern> *.txt | ls -rt

is not what I need, since the ls -lrtmerely outputs allfiles.

不是我需要的,因为ls -lrt仅输出所有文件。

采纳答案by Shawn Chin

Try:

尝试:

ls -rt *.txt | xargs grep -l <pattern>

We first use lsto list *.txtfiles and sort them by modification time (newest last), then for each entry run them through grepso we only print out files that contain the pattern.

我们首先使用ls列出*.txt文件并按修改时间(最新的最后)对它们进行排序,然后对每个条目运行它们,grep因此我们只打印出包含该模式的文件。

回答by NIK

I know this is an old question but thought of adding my suggestion for someone who is searching for the same..

我知道这是一个老问题,但我想为正在寻找相同问题的人添加我的建议。

for i in $(ls -rt *.txt); do grep <pattern> $i; done

for i in $(ls -rt *.txt); do grep <pattern> $i; done

回答by Kamaraju Kusumanchi

Here is another way

这是另一种方式

grep -l <pattern> *.txt | xargs ls -ltr --time-style="+%Y%m%d_%H%M"

For example

例如

$ grep -l argparse * | xargs ls -ltr --time-style="+%Y%m%d_%H%M"
-rwxr-xr-x 1 raju 197121   979 20171030_2323 list_dep.py
-rwxr-xr-x 1 raju 197121 14329 20180129_2216 grep_installed.py
-rwxr-xr-x 1 raju 197121  7517 20180129_2216 popsort.py

To just list the files without timestamps etc.,

只列出没有时间戳等的文件,

grep -l <pattern> * | xargs ls -1tr

For example

例如

$ grep -l argparse * | xargs ls -1tr
list_dep.py
grep_installed.py
popsort.py