Get the App
SLTechnology News&Howtos  ›  Servers  › 

How linux uses shell search to find text

Shulou Source: shulou.com Published: 2022-06-01 13:04:16 10月01日 Update

This article mainly introduces "linux how to use shell search to find text". In daily operation, I believe many people have doubts about how linux uses shell search to find text. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "how linux uses shell search to find text". Next, please follow the editor to study!

1. Use the find and xargs commands

The code is as follows:

Find dir | xargs grep str # dir refers to a directory

Find file | xargs grep str # file refers to a file 2.

The second method is to use the grep command directly

The code is as follows:

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

Grep-r str dir/* # recursively searches its subdirectories using the-r option

Grep str file # file refers to a file

3. The third method is to combine the above two.

The code is as follows:

#! / bin/bash

# find_str.sh

If [$#-lt "2]; then

Echo "Usage: `basename $0` path name [option]"

Exit 1

Fi

#!-r indicates recursive processing of subdirectories, and-I indicates ignoring case

Path=$1

Name=$2

Shift

Shift

For option in "$@"

Do

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"! = "$0"]; then

Echo "$file: $out"

Fi

}

Find_str ()

{

If [- d "$1"]; then

For file in $1max *

Do

If ["$dir_op" = "- r"-a-d "$file"]; then

Find_str $file $2

Elif [- f "$file"]; then

Grep_str_of_file $file $2

Fi

Done

Elif [- f "$1"]; then

Grep_str_of_file $1 $2

Fi

}

Usage

The code is as follows:

$find_str $path $name

At this point, the study on "how linux uses shell search to find text" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Search text code methods learning subitems subdirectories recursion commands files more directories help practical next usage size articles theory knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Shulou Technology Redmi Linux Xiaomi