命令打开包含给定数据的文件

时间:2022-01-04 03:03:36

I had this question in interview.

我在面试中问过这个问题。

He put a situation in front of me that there are 12 files in your Linux operating system. Give me a command which will open a file containing data "Hello"..

他在我面前展示了你的Linux操作系统中有12个文件。给我一个命令,它将打开一个包含数据“Hello”的文件。

I told him I just know grep command which will give you the names of files having "Hello" data.

我告诉他我只知道grep命令,它会告诉你有“Hello”数据的文件的名称。

Please tell me if there is any command to open a file in this way..

如果有任何命令可以用这种方式打开文件,请告诉我。

2 个解决方案

#1


1  

Assuming it will be only one file containing the word hello:

假设只有一个文件包含hello:

less $(grep -H "hello" *.txt | sed s/:.*//)

Here it is first capturing the file name using grep with -H parameter. Then using sed removing everything except the filename. And finally its using less to open the file.

这里,它首先使用带有-H参数的grep捕获文件名。然后使用sed删除除文件名之外的所有内容。最后,用更少的资源打开文件。

#2


1  

Maybe this could help:

也许这可以帮助:

$ echo "foo" > file1.txt
$ echo "bar" > file2.txt
$ grep -l foo * | xargs cat
foo

You have 2 files, and you are looking for the one with the string "foo" in it. Change cat with your command of choice to open files. Might try vi, emacs, nano, pico... (no, another flame war!)

您有两个文件,您正在寻找其中一个带有字符串“foo”的文件。使用您选择的命令更改cat以打开文件。可以试试vi, emacs, nano, pico…(不,另一个火焰战争!)

You may want to try a different approach if there are several files that contains the string you are looking for... Just thought of only one file containing the string.

如果有几个文件包含您正在寻找的字符串,您可能想尝试不同的方法。只考虑一个包含字符串的文件。

#1


1  

Assuming it will be only one file containing the word hello:

假设只有一个文件包含hello:

less $(grep -H "hello" *.txt | sed s/:.*//)

Here it is first capturing the file name using grep with -H parameter. Then using sed removing everything except the filename. And finally its using less to open the file.

这里,它首先使用带有-H参数的grep捕获文件名。然后使用sed删除除文件名之外的所有内容。最后,用更少的资源打开文件。

#2


1  

Maybe this could help:

也许这可以帮助:

$ echo "foo" > file1.txt
$ echo "bar" > file2.txt
$ grep -l foo * | xargs cat
foo

You have 2 files, and you are looking for the one with the string "foo" in it. Change cat with your command of choice to open files. Might try vi, emacs, nano, pico... (no, another flame war!)

您有两个文件,您正在寻找其中一个带有字符串“foo”的文件。使用您选择的命令更改cat以打开文件。可以试试vi, emacs, nano, pico…(不,另一个火焰战争!)

You may want to try a different approach if there are several files that contains the string you are looking for... Just thought of only one file containing the string.

如果有几个文件包含您正在寻找的字符串,您可能想尝试不同的方法。只考虑一个包含字符串的文件。