简体   繁体   English

如何打印与特定字符串匹配的所有行?

[英]How to print all lines that matches a particular string?

I am intending to print all the lines with their line numbers along with its location within a specific directory which matches a particular string我打算打印所有行及其行号及其在与特定字符串匹配的特定目录中的位置

Example ..例子..

/home/some_dir/file.txt -(LineNo) -(printing_thatlineitself)

I currently have 2 commands with me but both have some shortcomings我目前有 2 个命令,但都有一些缺点

find /home/some_dir -type f -exec grep -Hn "Text To Find" {} \;

This above find command seems to work accurately but the issue is that it works quite slow上面的 find 命令似乎可以准确地工作,但问题是它的工作速度很慢

find /home/some_dir -type f -print0 | xargs -0 grep -Hn -C2 "Text To Find"

This command works comparatively quite faster but it provides inaccurate results.此命令的运行速度相对较快,但提供的结果不准确。 It even prints those lines where my inputted string is not present at all它甚至打印我输入的字符串根本不存在的那些行

Can someone provide a solution that works accurately and is fast as well?有人可以提供一个既准确又快速的解决方案吗? PS / its fine if the solution doesn't use the find command to achieve this .it just has to be something I can directly run in CLI PS / 如果解决方案不使用 find 命令来实现这一点,那很好。它必须是我可以直接在 CLI 中运行的东西

正如评论中所建议的,可以使用 grep 非常有效地执行此操作

grep -IHnr "Text to find" .

-I : Process a binary file as if it did not contain matching data (to exclude binary files)

-H : Print the filename for each match

-n : Display the matched lines and their line numbers

-r : Recursively search subdirectories listed

"Text to find" : Search string

. : Directory for search (current directory)

I would not squeeze everything into one command.我不会将所有内容都压缩到一个命令中。 It is simpler to write a small shell script which combines several utilities.编写一个结合了多个实用程序的小型 shell 脚本会更简单。 For example,例如,

$ cat script.sh
#!/bin/sh   
IFS='
'
for i in `find . -type f`
do
    awk '
    /Text To Find/ {
        print FILENAME, NR
    }' "$i"
done
$ chmod +x script.sh
$ ./script.sh 
./script.sh 7

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

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