Last Updated:

How to find a line in files on Linux (Ubuntu)?

Ubuntu
 

How do I find a string in linux files?

A command-line utility called grep will help us with this. It looks for strings that match a regular expression and prints them to the console.

Note the following

  1. Use parentheses if the string contains spaces "command text".
  2. Remember about the spaces between the extensions {js,java}
  3. Do not use curly braces for a single extension {java} -> java

Below are the most useful commands that I use in my daily work, as well as other working commands found on the Internet:

Simple search for a string in a file

Command structure: grep string nameFile

Example of use: grep name file.txt

Searching for a string in a file ignoring case sensitivity

Command structure: grep string nameFile

Example of use: grep -i name file.txt

Find a string in the current directory

Command structure: grep string .

Example of use: grep name .

Find a string recursively

Command structure: grep -r string .

Example of use: grep -r name .

Find files that do not contain a specific string

Command structure: grep -L string *

Example of use: grep -L "foo" *

Recursively find a string only in certain files

Team structure:

grep string -r . —include=*.file extension

grep string -r . —include=*. {File extension, File extension2}

Example of use: grep "name=Main" -r . --include=*.java

Note! I will search for these commands only in those files that you have defined in the —include=* section. {...}

Recursively find a string other than certain extensions

Command structure: grep string -r . —exclude=*.{ File extension}

Example of use: grep "Serializable" -r . --exclude=*.{jar,js,index}

Recursively find a string in certain extensions, excluding the specified

Team structure:

grep string -r . —include=*.extensionFile —exclude=*.extensionFile2

grep string -r . —include=*. {File Extension, File Extension2} —exclude=*. {File extension3,File extension2}

Example of use: grep "name=Main" -r . --include=*.{java,html} --exclude=*.java

Note! The command above will not search in files with the extension .java