Find a specific word in files and list the lines

There are many situations when you might want to search for specific words in files. This can be obtained with the use of the Linux grep utility.

With the grep utility you can search in a single file, but you can also search recursively in all files from a directory.

To search in a single file, use:

# grep -n "texttofind" filename
root@web [/]# grep -n "lorem" /temp3/textfile2.txt
8:Nunc efficitur lorem eu dui malesuada tincidunt.
29:Praesent eu tortor sed lorem egestas mollis.
46:Morbi quis massa vel metus pharetra eleifend et non lorem.
79:Duis at diam vitae lectus finibus consequat malesuada nec lorem.
116:Nulla lacinia lorem eget quam porttitor elementum.
139:Nunc dignissim nunc rhoncus, vestibulum lorem sit amet, commodo mi.
142:Aenean hendrerit lorem eget nisi euismod, finibus aliquam enim maximus.
148:In sed lorem at libero vulputate efficitur eget non tortor.
157:Vestibulum quis lorem convallis, ultricies nunc non, lacinia mi.
root@web [/]#

To search in all files from a directory, use:

# grep -nr "texttofind" path
root@web [/]# grep -nr "lorem" /temp3
/temp3/textfile2.txt:8:Nunc efficitur lorem eu dui malesuada tincidunt.
/temp3/textfile2.txt:29:Praesent eu tortor sed lorem egestas mollis.
/temp3/textfile2.txt:46:Morbi quis massa vel metus pharetra eleifend et non lorem.
/temp3/textfile2.txt:79:Duis at diam vitae lectus finibus consequat malesuada nec lorem.
/temp3/textfile2.txt:116:Nulla lacinia lorem eget quam porttitor elementum.
/temp3/textfile2.txt:139:Nunc dignissim nunc rhoncus, vestibulum lorem sit amet, commodo mi.
/temp3/textfile2.txt:142:Aenean hendrerit lorem eget nisi euismod, finibus aliquam enim maximus.
/temp3/textfile2.txt:148:In sed lorem at libero vulputate efficitur eget non tortor.
/temp3/textfile2.txt:157:Vestibulum quis lorem convallis, ultricies nunc non, lacinia mi.
/temp3/textfile1:2:Cras vel velit et lorem dignissim placerat.
/temp3/textfile1:24:Aliquam id erat mattis, viverra lorem id, ultricies purus.
/temp3/textfile1:52:Suspendisse porttitor risus nec odio facilisis, sit amet iaculis lorem fermentum.
/temp3/textfile1:86:Duis consectetur dolor id lorem mattis sagittis.
/temp3/textfile1:105:Aenean a justo vel lorem tincidunt tincidunt at sed urna.
/temp3/textfile1:109:Nunc at tortor nec lorem ullamcorper eleifend quis vitae nibh.
/temp3/textfile1:127:Duis quis nibh consectetur, scelerisque lorem gravida, suscipit nisl.
/temp3/textfile1:132:Fusce et lorem a diam lacinia efficitur placerat vel mauris.
root@web [/]#

Some of the options for the grep command:

-r	to recursively search
-n	to display line numbers

For other useful options check the help file for the grep command with man grep

This Post Has 2 Comments

  1. istana168

    thank you for information

  2. istana168

    thank you for information

Leave a Reply