grep 命令

grep 命令用于查找文件里符合条件的文本。

语法

grep [选项]... PATTERN [FILE]...

  • PATTERN:要搜索的模式(正则表达式或简单字符串)。
  • FILE:要搜索的文件名。如果不提供文件名,则默认从标准输入读取数据并进行搜索,也可以使用通配符表示一类文件

选项

PATTERN正则表达式选项:

-E, --extended-regexp     PATTERN 是一个可扩展的正则表达式(缩写为 ERE)
-F, --fixed-strings       PATTERN 是一组由断行符分隔的定长字符串。
-G, --basic-regexp        PATTERN 是一个基本正则表达式(缩写为 BRE)
-P, --perl-regexp         PATTERN 是一个 Perl 正则表达式
-e, --regexp=PATTERN      用 PATTERN 来进行匹配操作
-f, --file=FILE           从 FILE 中取得 PATTERN
-i, --ignore-case         忽略大小写
-w, --word-regexp         强制 PATTERN 仅完全匹配字词
-x, --line-regexp         强制 PATTERN 仅完全匹配一行
-z, --null-data           一个 0 字节的数据行,但不是空行

输出控制选项:

  -m, --max-count=NUM       最多只匹配NUM次后停止
  -n, --line-number         输出的同时打印行号
      --line-buffered       每行输出清空
  -b, --byte-offset         输出的同时打印字节偏移
  -H, --with-filename       在每个匹配项前输出文件名
  -h, --no-filename         输出时不显示文件名前缀
      --label=LABEL         将LABEL 作为标准输入文件名前缀
  -o, --only-matching       只输出匹配部分,不输出匹配行其他内容
  -q, --quiet, --silent     只查找不输出匹配内容
      --binary-files=TYPE   assume that binary files are TYPE;
                            TYPE is 'binary', 'text', or 'without-match'
  -a, --text                不要忽略二进制文件 --binary-files=text
  -I                        equivalent to --binary-files=without-match
  -d, --directories=ACTION  如何处理目录,ACTION可以是'read', 'recurse', or 'skip'
  -r, --recursive           递归查找目录,同--directories=recurse
  -R, --dereference-recursive
                            likewise, but follow all symlinks
      --include=FILE_PATTERN
                            只搜索FILE_PATTERN匹配的文件
      --exclude=FILE_PATTERN
                            排除FILE_PATTERN匹配的文件
      --exclude-from=FILE   排除文件
      --exclude-dir=PATTERN directories that match PATTERN will be skipped.
  -L, --files-without-match 只打印没有匹配到的文件名
  -l, --files-with-matches  只打印有匹配的文件名
  -c, --count               只打印每个文件匹配到的次数
  -T, --initial-tab         make tabs line up (if needed)
  -Z, --null                print 0 byte after FILE nam

文件控制选项:

  -B, --before-context=NUM  打印匹配到文件上下文的前NUM 行
  -A, --after-context=NUM   打印匹配到文件上下文的后NUM 行
  -C, --context=NUM         打印匹配到文件上下文的前后NUM 行
  -NUM                      同 -C
  -U, --binary              do not strip CR characters at EOL (MSDOS/Windows)
  -u, --unix-byte-offsets   report offsets as if CRs were not there
                            (MSDOS/Windows)

实例

1、在当前目录中的日志文件(.log文件)查找含'Exception'的内容。此时,可以使用如下命令:

grep 'Exception' *.log

结果如下所示:

log2023-02-04_0.log:org.jflame.toolkit.cache.RedisAccessException: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
log2023-02-04_0.log:Caused by: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
log2023-02-04_0.log:Caused by: redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
log2023-02-04_0.log:Caused by: java.util.NoSuchElementException: Unable to validate object
log2023-02-04_0.log:org.jflame.toolkit.cache.RedisAccessException: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
log.log:org.jflame.toolkit.cache.RedisAccessException: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
log.log:Caused by: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
log.log:Caused by: redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
log.log:Caused by: java.util.NoSuchElementException: Unable to validate object

2、以递归的方式查找符合条件的文件。例如,查找指定目录/etc/acpi 及其子目录(如果存在子目录的话)下所有文件中包含字符串"update"的文件,并打印出该字符串所在行的内容,使用的命令为:

grep -r update /etc/acpi

输出结果如下:

$ grep -r update /etc/acpi #以递归的方式查找“etc/acpi”

#下包含“update”的文件

/etc/acpi/ac.d/85-anacron.sh:# (Things like the slocate updatedb cause a lot of IO.)

Rather than

/etc/acpi/resume.d/85-anacron.sh:# (Things like the slocate updatedb cause a lot of

IO.) Rather than

/etc/acpi/events/thinkpad-cmos:action=/usr/sbin/thinkpad-keys--update

3、反向查找。前面各个例子是查找并打印出符合条件的行,通过"-v"参数可以打印出不符合条件行的内容。

查找文件名中包含 test 的文件中不包含 test 的行,此时,使用的命令为:

grep -v test *test*

结果如下所示:

$ grep-v test* #查找文件名中包含test 的文件中不包含test 的行

testfile1:helLinux!

testfile1:Linis a free Unix-type operating system.

testfile1:Lin

testfile_1:HELLO LINUX!

testfile_1:LINUX IS A FREE UNIX-TYPE OPTERATING SYSTEM.

testfile_1:THIS IS A LINUX TESTFILE!

testfile_2:HELLO LINUX!

testfile_2:is a free unix-type opterating system.

4、log.log文件中查找含'Exception'的内容,并打印出上下文的前10行

$ grep -10 'Exception' log.log 
2023-02-06 09:47:54,978 ERROR[pool-4-thread-1] o.s.s.s.TaskUtils$LoggingErrorHandler - Unexpected error occurred in scheduled task.
org.jflame.toolkit.cache.RedisAccessException: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
	at org.jflame.toolkit.cache.SpringCacheClientImpl.setIfAbsent(SpringCacheClientImpl.java:126)
	at org.jflame.toolkit.lock.RedisLock.setNX(RedisLock.java:125)
	at org.jflame.toolkit.lock.RedisLock.lock(RedisLock.java:73)
	at com.ghgcn.support.job.AbstractJobWithDistribtedLock.execute(AbstractJobWithDistribtedLock.java:41)
	at sun.reflect.GeneratedMethodAccessor198.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
	at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool
	at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:204)
	at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:348)
	at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:129)
	at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:92)
	at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:79)
	at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:194)
	at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169)




返回软件开发辅助网 | 常用命令列表

shell语法手册