- Grep Command in Linux (Find Text in Files)
- grep Command Syntax #
- Search for a String in Files #
- Invert Match (Exclude) #
- Using Grep to Filter the Output of a Command #
- Recursive Search #
- Show Only the Filename #
- Case Insensitive Search #
- Search for Full Words #
- Show filename and line number in grep output
- 5 Answers 5
- How to get line number from grep?
- 4 Answers 4
- You must log in to answer this question.
- Related
- Hot Network Questions
- Subscribe to RSS
- How to display line number while doing grep on a file
- You must log in to answer this question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
Grep Command in Linux (Find Text in Files)
The grep command stands for “global regular expression print”, and it is one of the most powerful and commonly used commands in Linux.
grep searches one or more input files for lines that match a given pattern and writes each matching line to standard output. If no files are specified, grep reads from the standard input, which is usually the output of another command.
In this article, we will show you how to use the grep command through practical examples and detailed explanations of the most common GNU grep options.
grep Command Syntax #
The syntax for the grep command is as follows:
grep [OPTIONS] PATTERN [FILE. ]
The items in square brackets are optional.
- OPTIONS — Zero or more options. Grep includes a number of options that control its behavior.
- PATTERN — Search pattern.
- FILE — Zero or more input file names.
To be able to search the file, the user running the command must have read access to the file.
Search for a String in Files #
The most basic usage of the grep command is to search for a string (text) in a file.
For example, to display all the lines containing the string bash from the /etc/passwd file, you would run the following command:
The output should look something like this:
root:x:0:0:root:/root:/bin/bash linuxize:x:1000:1000:linuxize:/home/linuxize:/bin/bash
If the string includes spaces, you need to enclose it in single or double quotation marks:
grep "Gnome Display Manager" /etc/passwd
Invert Match (Exclude) #
To display the lines that do not match a pattern, use the -v ( or —invert-match ) option.
For example, to print the lines that do not contain the string nologin you would use:
root:x:0:0:root:/root:/bin/bash colord:x:124:124::/var/lib/colord:/bin/false git:x:994:994:git daemon user:/:/usr/bin/git-shell linuxize:x:1000:1000:linuxize:/home/linuxize:/bin/bash
Using Grep to Filter the Output of a Command #
A command’s output can be filtered with grep through piping, and only the lines matching a given pattern will be printed on the terminal.
For example, to find out which processes are running on your system as user www-data you can use the following ps command:
www-data 18247 12675 4 16:00 ? 00:00:00 php-fpm: pool www root 18272 17714 0 16:00 pts/0 00:00:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn www-data www-data 31147 12770 0 Oct22 ? 00:05:51 nginx: worker process www-data 31148 12770 0 Oct22 ? 00:00:00 nginx: cache manager process
You can also chain multiple pipes in on command. As you can see in the output above there is also a line containing the grep process. If you don’t want that line to be shown pass the output to another grep instance as shown below.
ps -ef | grep www-data | grep -v grep
www-data 18247 12675 4 16:00 ? 00:00:00 php-fpm: pool www www-data 31147 12770 0 Oct22 ? 00:05:51 nginx: worker process www-data 31148 12770 0 Oct22 ? 00:00:00 nginx: cache manager process
Recursive Search #
To recursively search for a pattern, invoke grep with the -r option (or —recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.
To follow all symbolic links , instead of -r , use the -R option (or —dereference-recursive ).
Here is an example showing how to search for the string linuxize.com in all files inside the /etc directory:
The output will include matching lines prefixed by the full path to the file:
/etc/hosts:127.0.0.1 node2.linuxize.com /etc/nginx/sites-available/linuxize.com: server_name linuxize.com www.linuxize.com;
If you use the -R option, grep will follow all symbolic links:
Notice the last line of the output below. That line is not printed when grep is invoked with -r because files inside the Nginx’s sites-enabled directory are symlinks to configuration files inside the sites-available directory.
/etc/hosts:127.0.0.1 node2.linuxize.com /etc/nginx/sites-available/linuxize.com: server_name linuxize.com www.linuxize.com; /etc/nginx/sites-enabled/linuxize.com: server_name linuxize.com www.linuxize.com;
Show Only the Filename #
To suppress the default grep output and print only the names of files containing the matched pattern, use the -l ( or —files-with-matches ) option.
The command below searches through all files ending with .conf in the current working directory and prints only the names of the files containing the string linuxize.com :
The output will look something like this:
The -l option is usually used in combination with the recursive option -R :
Case Insensitive Search #
By default, grep is case sensitive. This means that the uppercase and lowercase characters are treated as distinct.
To ignore case when searching, invoke grep with the -i option (or —ignore-case ).
For example, when searching for Zebra without any option, the following command will not show any output i.e there are matching lines:
But if you perform a case insensitive search using the -i option, it will match both upper and lower case letters:
grep -i Zebra /usr/share/words
Specifying “Zebra” will match “zebra”, “ZEbrA” or any other combination of upper and lower case letters for that string.
Search for Full Words #
When searching for a string, grep will display all lines where the string is embedded in larger strings.
For example, if you search for “gnu”, all lines where “gnu” is embedded in larger words, such as “cygnus” or “magnum” will be matched:
Show filename and line number in grep output
I am trying to search my rails directory using grep. I am looking for a specific word and I want to grep to print out the file name and line number. Is there a grep flag that will do this for me? I have been trying to use a combination of -n and -l but these are either printing out the file names with no numbers or just dumping out a lot of text to the terminal which can’t be easily read. ex:
5 Answers 5
I think -l is too restrictive as it suppresses the output of -n . I would suggest -H ( —with-filename ): Print the filename for each match.
If that gives too much output, try -o to only print the part that matches.
This answer worked out also for me. I was in need of searching recursively and used this example command: grep -Hnor «localhost» . This listet up all matches with file name and line number, short and concise.
grep -rin searchstring * | cut -d: -f1-2
This would say, search recursively (for the string searchstring in this example), ignoring case, and display line numbers. The output from that grep will look something like:
/path/to/result/file.name:100: Line in file where 'searchstring' is found.
Next we pipe that result to the cut command using colon : as our field delimiter and displaying fields 1 through 2.
When I don’t need the line numbers I often use -f1 (just the filename and path), and then pipe the output to uniq , so that I only see each filename once:
grep -ir searchstring * | cut -d: -f1 | uniq
How to get line number from grep?
I would like to know what line has the following text, I tried adding -n , but it did not work. I tried adding | grep -n * , but it did something weird. What I would like to see (I don’t care about format) is
4 Answers 4
get line number of a pattern!
if you want to get only the line number as output add another grep command to it !
grep -n "pattern" file.txt | grep -Eo '^[^:]+'
You should put -e at the end of the options list: grep -rne coll *
To grep a pattern in a specific file, and get the matching lines:
or using cut as suggested by @wjandrea:
grep -n | cut -f1 -d: | sort -u
- is a quoted glob pattern (use option -E for regexp);
- is the file you are interested in;
- the first pipe awk . filters the line numbers in the output of grep (before : on each line);
- the second pipe ensures that line numbers only appear once.
#This shows only the line number. #i --> case-insensitive, n --> line number var="APPLE";targetFile="targetFile.txt" numLin=$(grep -in $var $targetFile | cut -d':' -f1); echo $numLine;
You must log in to answer this question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.12.43529
Ubuntu and the circle of friends logo are trade marks of Canonical Limited and are used under licence.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to display line number while doing grep on a file
There is the option -n , and many more in the manual page, worth reading.
It is probably worth noting that using -n with -l does not work. -l will take precedence and only the name of the file will be printed.
grep -n prefixes each line of output with the line number in the input file. Is this what you are looking for?
alias grep=’grep -inE —color=auto’
This will color the match as well for easy reading.
Have you checked cat -n ‘filename’ . This will print the line numbers.
cat -n /boot/config | grep CONFIG_PM_ADVANCED_DEBUG
cat will -n[umber] the lines and | (filter) through grep looking only for lines with CONFIG_PM. in them
the resulting output will be line number; the text of the line and the string
cat -n[umber lines] /Path/to/filename | grep -i[gnor case (optional)] STRING_TO_LOOK_FOR
Welcome to U&L. I edited your post, so it utilizes the formatting possibilities of the site a bit more. Please review the changes (with the edit history), so your future answers (and questions) might look better. It is also not necessary to «sign» your post, your name is posted with your profile on all answers
You must log in to answer this question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.12.43529
Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
This site is not affiliated with Linus Torvalds or The Open Group in any way.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.