Linux uses Shell search to find text in several ways to share

Source: Internet
Author: User

The size of the log is very large, the server is generally Linux, HP, AIX, and so on, every time the download back to the trouble of the deadly, in the open source China to see the following content, very practical.

1. Use the Find and Xargs commands

The code is as follows:

Find Dir | Xargs grep str # dir refers to a directory

Find File | The Xargs grep str # file refers to a file 2.

The 2nd option is to use the grep command directly

The code is as follows:

grep str dir/* # dir refers to a directory but does not recursively search its subdirectories

Grep-r Str dir/* #使用-r option to recursively search its subdirectories

grep str file #file是指某个文件

3. The 3rd approach is to synthesize the above two types of

The code is as follows:

#!/bin/bash

#find_str. Sh

If [$#-lt "2"]; Then

echo "Usage: ' basename $ ' path name [option]"

Exit 1

Fi

#!-r represents the recursive processing of subdirectories,-I indicates that the case is ignored

Path=$1

Name=$2

Shift

Shift

For option in "$@"

Todo

Case $option in

-R) dir_op= "-R"

;;

-i) lu_op= "-I"

;;

*) If [-N "$option"]; Then

echo "Invalid option"

Exit 1

Fi

;;

Esac

Done

Grep_str_of_file ()

{

File=$1

Str=$2

out=$ (grep-n $lu _op "$str" "$file")

If [-N "$out"-A "$file"!= "$"]; Then

echo "$file: $out"

Fi

}

Find_str ()

{

If [-D "$"]; Then

For file in $1/*

Todo

If ["$dir _op" = "R"-a-d "$file"]; Then

FIND_STR $file $

elif [F "$file]"; Then

Grep_str_of_file $file $

Fi

Done

Elif [-F "$]"; Then

Grep_str_of_file $ $

Fi

}

How to use

The code is as follows:

$ find_str $path $name

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.