Search text inside files

Sometimes when we work in *nix systems we need to find some text inside files, to perform this task quickly and easily we have some command line tools that can help us.

One way to do it, it is using the tool find.

find . -type f | xargs grep "searchTerm"

Where we have:

  • find: Command line tool in *nix systems that search for files in a directory hierarchy.
  • path: In our case “.”. Folder where the search is going to start.
  • -type: Type of file that are going to be taken in consideration during the search.
  • xargs: Command line tool in *nix systems that build and execute command lines from standard input.
  • grep: Command line tool in *nix systems that print lines matching a pattern.
  • searchTerm: Word that we are looking for.

When we execute this command, a list of results with file names and the content of the lines where our searchTerm appears will be showed.

Another option is to use the command grep.

grep -ir "searchTerm" .

Where we have:

  • grep: Command line tool in *nix systems that print lines matching a pattern.
  • -i: Case insensitive.
  • -r: Recursive.
  • -l: Print only file names (Not in the above command but, sometimes, interesting option).
  • searchTerm: Word that we are looking for.

When we execute this command, a list of results with file names and the content of the lines where our searchTerm appears will be showed, except if we have used the option -l, in this case, only file names will be showed.

See you.

Advertisements
Search text inside files

Leave a Reply

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 / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s