Linux基本命令行搜索操作之&&grep命令

Linux基本命令行搜索操作之&&grep命令

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

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 用于输出匹配的文件。

4. 如果需要找出带有’-'字符

[root@server4 ~]# man xargs | grep "\-I"
       xargs  [-0prtx] [-E eof-str] [-e[eof-str]] [--eof[=eof-str]] [--null] [-d delimiter] [--delimiter delimiter] [-I replace-str] [-i[replace-str]] [--replace[=replace-str]] [-l[max-lines]] [-L
       -I replace-str
              This  option  is  a synonym for -Ireplace-str if replace-str is specified.  If the replace-str argument is missing, the effect is the same as -I{}.  This option is deprecated; use -I
       The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard.  Therefore you should use -L and -I instead, respectively.
       The -L option is incompatible with the -I option, but perhaps should not be.
       When you use the -I option, each line read from the input is buffered internally.   This means that there is an upper limit on the length of input line that xargs will accept when used with
       the -I option.  To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure
       somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}'

你可能感兴趣的:(Linux)