74

I have a file in Linux, I would like to display lines which contain a specific string in that file, how to do this?

mfaani
  • 33,269
  • 19
  • 164
  • 293
alwbtc
  • 28,057
  • 62
  • 134
  • 188

5 Answers5

129

The usual way to do this is with grep, which uses a pattern to match lines:

grep 'pattern' file

Each line which matches the pattern will be output. If you want to search for fixed strings only, use grep -F 'pattern' file. fgrep is shorthand for grep -F.


You can also use sed:

sed -n '/pattern/p' file

Or awk:

awk '/pattern/' file
knittl
  • 246,190
  • 53
  • 318
  • 364
18

Besides grep, you can also use other utilities such as awk or sed

Here is a few examples. Let say you want to search for a string is in the file named GPL.

Your sample file

$ cat -n GPL 
     1    The GNU General Public License is a free, copyleft license for
     2    The licenses for most software and other practical works are designed
     3  the GNU General Public License is intended to guarantee your freedom to
     4  GNU General Public License for most of our software;

1. grep

$ grep is GPL 
  The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to

2. awk

$ awk /is/ GPL 
  The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to

3. sed

$ sed -n '/is/p' GPL
  The GNU General Public License is a free, copyleft license for
the GNU General Public License is intended to guarantee your freedom to
mfaani
  • 33,269
  • 19
  • 164
  • 293
13

/tmp/myfile

first line text
wanted text
other text

the command

$ grep -n "wanted text" /tmp/myfile | awk -F  ":" '{print $1}'
2

The -n switch to grep prepends any matched line with the line number (followed by :), while the second command uses the colon as a column separator (-F ":") and prints out the first column of any line. The final result is the list of line numbers with a match.

Ilario
  • 662
  • 11
  • 23
deFreitas
  • 4,196
  • 2
  • 33
  • 43
  • An answer should contain explanation of the given command. Besides, the OP was probably asking for the actual line, not the line number – Ilario Aug 04 '21 at 08:01
  • @Ilario Alright, feel free to give your edit contribution to the answer. – deFreitas Aug 07 '21 at 16:17
8

The grep family of commands (incl egrep, fgrep) is the usual solution for this.

$ grep pattern filename

If you're searching source code, then ack may be a better bet. It'll search subdirectories automatically and avoid files you'd normally not search (objects, SCM directories etc.)

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

Write the queue job information in long format to text file

qstat -f > queue.txt

Grep job names

grep 'Job_Name' queue.txt

FVD
  • 11
  • 1