Linux: grep command

来源:互联网 发布:xp下安装linux双系统 编辑:程序博客网 时间:2024/06/04 18:15

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

Content:

    • Content
    • Search for the given string in a single file
    • Case insensitive search using grep -i
    • Match regular expression in files
    • Checking for full words not for sub-strings using grep -w
    • Displaying lines beofreafteraround the match using grep -A -B and -C
    • Highlighting the search using GREP_OPTIONS
    • Searching in all files recursively using grep -r
    • Counting the number of matches using grep -c
    • Display only the file names which matches the given pattern using grep -l
    • Show only the matched string
    • Show line number while displaying the output using grep -n
    • Summary


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

0 0
原创粉丝点击