Basic grep question

Shell : Bash shell (Fedora 26)

In the below text file (output.txt), I need to find all lines starting with the pattern pc . As you can see, only one line matches this condition ( pc hello world ).

But, my below 3 attempts return wrong output. How do I use the grep command correctly here ?

 # cat output.txt
  sunrpc                331776  1
  crct10dif_pclmul       16384  0
  crc32_pclmul           16384  0
  shpchp                 36864  0
  snd_pcm               102400  4 snd_hda_intel,snd_hda_codec,snd_hda_core,snd_hda_codec_hdmi
  snd_timer              32768  2 snd_seq,snd_pcm
  lpc_ich                24576  0
  pc hello world

  # Attempt1
  # It returns any line with the the pattern pc in it which is not what I want
  # grep 'pc' output.txt
  sunrpc                331776  1
  crct10dif_pclmul       16384  0
  crc32_pclmul           16384  0
  shpchp                 36864  0
  snd_pcm               102400  4 snd_hda_intel,snd_hda_codec,snd_hda_core,snd_hda_codec_hdmi
  snd_timer              32768  2 snd_seq,snd_pcm
  lpc_ich                24576  0
  pc hello world
  # 


  # Attempt2
  # No output returned at all
  # grep 'pc^' output.txt



  # Attempt3 
  # I think this gives the same wrong output as Attempt1 
  # grep 'pc*' output.txt
  sunrpc                331776  1
  crct10dif_pclmul       16384  0
  crc32_pclmul           16384  0
  shpchp                 36864  0
  snd_pcm               102400  4 snd_hda_intel,snd_hda_codec,snd_hda_core,snd_hda_codec_hdmi
  snd_timer              32768  2 snd_seq,snd_pcm
  lpc_ich                24576  0
  pc hello world
  # 

Normally you would use:

grep '^pc'

I do not know if the leading spaces are present in the actual file. In that case you would need something like:

grep '^[[:blank:]]*pc'

--
Note: on Solaris use /usr/xpg4/bin/grep

1 Like

Print if the first word is pc (white space delimited)

awk '$1=="pc"'
1 Like

You could be right Scrutinizer. All those lines except pc hello world comes from lsmod command in Linux. It could have leading spaces.

Hi MadeInGermany,
What does the 2 equal operators == in your awk solution do ?

In awk the == operator compares two numbers or strings, in this case strings.
If they are equal the result is "true", a non-zero. The default action for a non-zero is {print} .
You can write this more explicit

awk '$1=="pc" { print }'

or

awk '{ if ($1=="pc") { print } }'

or even

awk '{ if ($1=="pc") { print $0 } }'
1 Like