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
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.
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.
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.
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).
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With