Live data from Hacker News

Grep flags – the good stuff

zwischenzugs.com

1–10 of 53 posts

Re: Grep flags – the good stuff

#4
An amazing grep trick that I use all the time: The -e flag can be used to search for multiple terms. A blank -e will search for null. Thus:

Lets assume we have a log file with a bunch of relevant stuff, I want to highlight my search term, BUT I also want to keep all the other lines around for context:

  $ dmesg
  ...SNIP...
  [2334597.539661] sd 1:0:0:0: [sdb] Attached SCSI removable disk
  [2334597.548919] sd 1:0:0:0: [sdb] 57280429 512-byte logical blocks: (29.3 GB/27.3  GiB)
  [2334597.761895] sd 1:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
  [2334597.761900] sdb: detected capacity change from 0 to 57280429
  [2334597.772736]  sdb:
  [2334631.115664] sdb: detected capacity change from 57280429 to 0
  ...SNIP...
A simple grep, will only return the selected lines:

  $ dmesg | grep capacity
  [2334597.761900] sdb: detected capacity change from 0 to 57280429
  [2334631.115664] sdb: detected capacity change from 57280429 to 0
  
But I want all lines:

  $ dmesg | grep --color -e capacity -e ''
  ...SNIP...
  [2334597.539661] sd 1:0:0:0: [sdb] Attached SCSI removable disk
  [2334597.548919] sd 1:0:0:0: [sdb] 57280429 512-byte logical blocks: (29.3 GB/27.3  GiB)
  [2334597.761895] sd 1:0:0:0: [sdb] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
  *[2334597.761900] sdb: detected capacity change from 0 to 57280429*
  [2334597.772736]  sdb:
  *[2334631.115664] sdb: detected capacity change from 57280429 to 0*
  ...SNIP...

The null trick also works well on directories with many small files, like /proc/ or /sys/. Say, for example, you wanted to get the filename and value of each file:

  $ grep -R '' /sys/module/iwlwifi/parameters/
  /sys/module/iwlwifi/parameters/nvm_file:(null)
  /sys/module/iwlwifi/parameters/debug:0
  /sys/module/iwlwifi/parameters/swcrypto:0
  /sys/module/iwlwifi/parameters/power_save:N
  /sys/module/iwlwifi/parameters/lar_disable:N
  ...SNIP...

Re: Grep flags – the good stuff

#5
post #2

I have problems remembering the mnemonic for -A and -B. I can't get it straight whether it's "before" and "after" or "above" and "below". I always just try one then the other!

I've never had trouble remembering, but after reading this comment I'm afraid I might start :(

(joking)

Re: Grep flags – the good stuff

#8
post #2

I have problems remembering the mnemonic for -A and -B. I can't get it straight whether it's "before" and "after" or "above" and "below". I always just try one then the other!

The way I remember this is by keeping in mind that grep processes the area of the search as a stream of discrete lines by looking at each line individually. "Above/below" are concepts on the stream level, and "after/before" are on the line level.
Post reply on HN