Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep just lines contain specific string in grep?

Tags:

text

grep

I have text file. I need print just these lines which contain one of specific string for example: Text file:

Car, bold 231212 /Fds
House pen 232123 /RYF
game kon 342442 /ksgj
mess three 42424 /UTR

And I need just keep lines contain Fds or UTR

Output:

Car, bold 231212 /Fds
mess three 42424 /UTR

How to do these in grep?

Thank you

like image 350
user1844845 Avatar asked Aug 26 '13 20:08

user1844845


People also ask

How do you grep all lines containing strings?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.

How do you grep surrounding lines?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.

How do you grep words only?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.

How do you exclude lines in grep?

Exclude Words and Patterns To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters).


2 Answers

Try doing this, the OR operator is the pipe : | :

grep -E 'Fds|UTR' file

or

grep -E '(Fds|UTR)' file

or

grep -P '(?:Fds|UTR)' file

or

grep 'Fds\|UTR' file
like image 126
Gilles Quenot Avatar answered Oct 17 '22 13:10

Gilles Quenot


This can be done with a single command, fortunately. grep can be used to search either files directly or any data piped to it. In this case, we'll just use it to search a single file.

grep can use regular expressions, which will be used to allow for "or" behavior (as denoted by the "|", or pipe symbol) when searching. The command you're looking for should be

grep 'Fds\|UTR' filename

That backslash is important. Without it, grep searches for the string "Fds|UTR", which obviously doesn't exist in the search text.

Alternately, one could use egrep.

egrep 'Fds|UTR' filename
like image 39
Andy Avatar answered Oct 17 '22 11:10

Andy