Linux: grep command

本文详细介绍了Linux下grep命令的多种实用用法,包括单文件搜索、不区分大小写的搜索、正则表达式匹配、全词匹配、显示匹配前后及周边行、高亮显示、递归搜索所有文件、计数匹配项、仅显示文件名、只显示匹配字符串及显示行号等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Source:
1. 15 Practical Grep Command Examples In Linux / UNIX

Content:


Search for the given string in a single file

grep “string” filename
grep “string” filenmma*

Case insensitive search using grep -i

grep -i “string” filename

Match regular expression in files

grep “line*empty” filename

Checking for full words not for sub-strings using grep -w

It can be used to search for a word, avoiding match the substring.

grep -w “is” filename

Displaying lines beofre/after/around the match using grep -A, -B and -C

“When doing a grep on a huge file, it may be useful to see more lines after the match. You might feel handy if grep can show you not only the matching lines but also the lines after/before/around the match”

-A: after -B: before -C: around

grep -A 3 “string” filename
(print matching lines, along with the 3 lines after it)

grep -B “string” filename
grep -C “string” filename

Highlighting the search using GREP_OPTIONS

“As grep prints out lines from the files by the pattern/string you had given, if you wanted it to highlight which part matches the line, then you need to follow the following way”

$export GREP_OPTIONS=’–color=auto’ GREP_COLOR=’100;8’

Searching in all files recursively using grep -r

grep -r “string” *

“When you want to display the lines which does not matches the given string, use the option -v as shown below. This example will display all the lines that did not match the word ‘go’”

grep -v “go” filename

Counting the number of matches using grep -c

“When you want to count that how many lines matches the given string, then use the option -c”

grep -c “string” filename

Display only the file names which matches the given pattern using grep -l

grep -l “string” *
output: demo_file, demo_file1

Show only the matched string

show out only the matched string

grep -o “regre pattern” filename

Show line number while displaying the output using grep -n

grep -n “string” filename

Summary

grep -option “string”

-r: recursively

-i: insensitive
-w: word

-A/-B/-C : after/before/around
-v: invert match
-c: counting number
-l: display the file name
-o: show only the matched string
-n: show out the index of lines

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值