Print the Lines with Particular String in File Linux-2

Print the Lines with Particular String in File Linux

To print the lines of a file that contain a specific string or text, we use linux grep command.

Syntax:

grep -n "string"  filename

grep -n "devops" hello.txt
1:devops dfsfsg
6:devops dsf dfsf dfds

Here we are giving the input to the command like which file you want to search. it will search in that file for that particular string or text and it will print the lines with line numbers.

-n represent print the lines with line numbers

Search Recursively in a Directory

in the above example we are giving input to the command like which file you want to search. But sometimes we will get a situation like we have to find a files names and lines containing that particular string in a Particular path or directory.

Syntax:

grep -nr "string"  /path

grep -nr "devops" ./docker
/Users/fgfd/docker/hello.txt:1:devops dfsfsg
/Users/fgfd/docker/hello.txt:6:devops dsf dfsf dfds

Here we are searching for a string in a list files in docker directory. So it will search all the files in docker directory and it will print the file name and line numbers that containing particular string.

-r recusrsively search all files in the directory

-n represent print the lines with line numbers

Print the Filenames Containing Particular String

to print only filenames that containing particular string we can use grep command with -lr.

Syntax:

grep -rl "devops" ./docker

grep -rl "devops" ./abcd
./abcd/hello.txt
./abcd/tt/sf.txt

-l represents show the file name not the lines

-r represents recursive search.

Here you can see it will print only filenames.

  • Print the Lines with Particular String in File Linux
  • Print the Lines with Particular text in File Linux

Leave a Reply

Your email address will not be published. Required fields are marked *