Không không sắc sắc, sắc sắc không không

Finding a File containing a particular text string in Linux server

Q. I’ve been using Linux for a while on my server and have a large collection of text file everywhere. I’m interested in learning about searching a text string. Can you tell me – how do I find a file containing a particular text string in Linux server?

A. I have to admit that there are tens and thousands of text files in Linux server. Finding and locating those files can be done with find command. Unfortunately find command cannot look inside a text file for a string.

You need to use grep command. grep searches the given input FILEs for lines containing a match or a text string.

grep command form (syntax)

grep “text string to search” directory-path

Examples

For example search for a string called redeem reward in all text files located in /home/tom/*.txt directory, use

$ grep "redeem reward" /home/tom/*.txt

Task: Search all subdirectories recursively

You can search for a text string all files under each directory, recursively with -roption:

$ grep -r "redeem reward" /home/tom

Task: Only print filenames

By default, grep command prints the matching lines You can pass -H option to print the filename for each match.

$ grep -H -r “redeem reward” /home/tom

Output:

...
filename.txt: redeem reward
...

To just print the filename use cut command as follows:

$ grep -H vivek /etc/* -R | cut -d: -f1

Output:

...
filename.txt
...

Gửi phản hồi

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Thay đổi )

Twitter picture

You are commenting using your Twitter account. Log Out / Thay đổi )

Facebook photo

You are commenting using your Facebook account. Log Out / Thay đổi )

Connecting to %s

Mây thẻ

Follow

Get every new post delivered to your Inbox.