0
点赞
收藏
分享

微信扫一扫

你不知道的grep命令

龙驹书房 2022-01-28 阅读 92


1.搜索包含指定内容的文件

  • 例如:搜索​​/root​​​下所有文件中是否包含​​"hello spark"​​的文件,使用如下命令:
[root@localhost ~]# grep "hello spark" /root/*.*
/root/word.txt:hello spark
  • 例如:搜索指定路径下的指定文件是否包含某一个字符串,使用如下命令:
[root@localhost ~]# grep "spark" /root/word.txt
hello spark
  • 注:实验环境的文件如下:
[root@localhost ~]# ll
total 1
-rw-r--r--. 1 root root 58 Apr 5 02:21 word.txt

需要注意的是,如果没有加任何参数,grep命令的搜索结果只显示出一行

2.显示文件中包含某字符串的行及内容

​grep -n [string] [filepath]​

[root@littlelawson ~]# grep -n hadoo /root/word.txt 
4:hello hadoop
7:spark is better than hadoop in streaming calculating
8:But when the data size is at PB level the hadoop is more effective

3.常用参数

-i, --ignore-case
Ignore case distinctions in both the PATTERN and the input files. (-i is specified by POSIX.)

-L, --files-without-match
Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.

-l, --files-with-matches
Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by
POSIX.)

-n, --line-number
Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.)

-r, --recursive
Read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -d recurse option.

​-n​​ 用于输出匹配的行号;

​-l​​ 用于输出匹配的文件。

3.1 输出匹配行的上下行

有些时候,我们需要知道grep 命令查找到的该行上下文的几行,这个时候就可以用​​-C​​​, ​​-B​​​, ​​-A​​ 参数,分别代表:


  • 前后几行(Center)
  • 前几行(Before)
  • 后几行 (After)

下面给出一个示例:

你不知道的grep命令_hadoop



举报

相关推荐

0 条评论