Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for a text in specific files in unix

Tags:

grep

unix

I am using Ubuntu machine and tried with below commands to search for a text:

This command to check if the word is present in a given directory recursively:

1) Here <hello> is the word which I am search for and it searches recursively in all files starting from current directory. It is working fine.

grep -r "<hello>" .

2) Now I want to restrict the search to only specific files, say to xml files only:

grep --include=\*.{java} -rnw '/home/myfolder/' -e "<hello>"

This time the command is taking more time and finally not giving any results. But my files has the content.

I have gone through this link - How do I find all files containing specific text on Linux? for writing my second command.

Is there any issue with my second command? Also is there an alternate command that performs fast?

like image 492
learner Avatar asked Jun 12 '15 10:06

learner


People also ask

How do I search for a specific text in a file in Linux?

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

How do I find all files containing specific text in Unix?

Without a doubt, grep is the best command to search a file (or files) for a specific text. By default, it returns all the lines of a file that contain a certain string. This behavior can be changed with the -l option, which instructs grep to only return the file names that contain the specified text.

How do I search for text in a file?

In many applications, you can use the Ctrl + F shortcut keys to open the Find option. On an Apple running macOS, you can use Command + F to open the find option. Finding text in a Word document.


2 Answers

It might be better to use find, since grep's include/exclude can get a bit confusing:

find -type f -name "*.xml" -exec grep -l 'hello' {} +

This looks for files whose name finishes with .xml and performs a grep 'hello' on them. With -l (L) we make the file name to be printed, without the matched line.

Explanation

  • find -type f this finds files in the given directory structure.
  • -name "*.xml" selects those files whose name finishes with .xml.
  • -exec execute a command on every result of the find command.
  • -exec grep -l 'hello' {} + execute grep -l 'hello' on the given file. With {} + we are refering to the matched name (it is like doing grep 'hello' file but refering to the name of the file provided by the find command). Also, grep -l (L) returns the file name, not the match itself.
like image 152
fedorqui 'SO stop harming' Avatar answered Oct 06 '22 00:10

fedorqui 'SO stop harming'


This is working for me, searching *.xml and *.java files, with GNU grep:

grep --include=\*.{xml,java} -rl '/path' -e 'hello'

In your question you had -w as flag, that means to match the whole word.

like image 33
chaos Avatar answered Oct 06 '22 00:10

chaos