简体   繁体   English

在Linux中查找某个文件并打印其创建和修改时间

[英]Looking up for a certain file in Linux and print its creation and modification time

I want to find some file(s) in a Linux directory based on a certain text that it/they have.我想根据它/他们拥有的特定文本在 Linux 目录中找到一些文件。 Once I figured out the file(s) I want to print the creation and modification time.一旦我找出文件,我想打印创建和修改时间。

For example, I have a directory X that has four files, namely: x1.txt, x2.txt, x3.text, and x4.txt with the following info.例如,我有一个目录 X,它有四个文件,即:x1.txt、x2.txt、x3.text 和 x4.txt,其中包含以下信息。

x1.txt

Name: Mark
Age: 22
Country: USA

x2.txt

Name: Jiff
Age: 26
Country: USA

x3.txt

Name: Sarah
Age: 30
Country: Canada

x4.txt

Name: Heather
Age: 23
Country: USA

What I want is print the creation and modification time of the file(s) that contain(s) "Country: Canada" text我想要的是打印包含“国家:加拿大”文本的文件的创建和修改时间

What i have done is I just figured out the files in this format我所做的是我只是想出了这种格式的文件

# echo $(grep -rn 'Country: Canada' *)

And I got我得到了

x3.txt:3:Country: Canada

I need to firstly extract the file name(s), then use the name(s) as input for a time command to get the creation and modification time.我需要首先提取文件名,然后使用名称作为时间命令的输入来获取创建和修改时间。

Use the -l option for grep to only list the file names:使用 grep 的-l选项仅列出文件名:

grep -lrn 'Country: Canada' *

To print the create/mod time of a file, use stat :要打印文件的创建/修改时间,请使用stat

stat <file>

You can format the output how you like:您可以按照自己的喜好格式化 output:

stat --printf "Created: %w\nModified: %y\n"

Putting it all together, you can send the output list of the grep to the input list of stat via the xargs command:综上所述,您可以通过xargs命令将 grep 的 output 列表发送到 stat 的输入列表:

grep -lrn 'Country: Canada' * | xargs stat --printf "Created: %w\nModified: %y\n"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM