0

How do I grep something and prevent the phrase appearing in the results?

I am trying to get only the MAC address from multiple systems and want only the MAC address in the results.

ipmitool lan print | grep "MAC Address             : "
# => MAC Address             : aa:bb:cc:dd:ee:ff

I got as far using google as trying is by adding -oP and \K\w+ but for some reason it only get's the first 2 digits of the MAC:

ipmitool lan print | grep -oP "MAC Address             : \K\w+"
# => aa

I understand the -o will only show the matched text which is why the MAC address is not being shown up and -P used with \K will prevent everything in-between from showing up but not sure what exactly to put after \w+ to make the rest of the MAC address show up.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Andy
  • 27
  • 2

1 Answers1

0

You can match it with

grep -oP 'MAC Address : \K\S+' file

Here,

  • -o - extracts the matched texts, not whole lines
  • P - enables the PCRE regex syntax
  • MAC Address : - matches a literal text
  • \K - match reset operator that discards the text matched so far from the memory match buffer
  • \S+ - one or more non-whitespace chars.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 2
    `grep -P` is not portable, though. The traditional solution would be `sed -n 's/.*MAC Address : //p'` or perhaps `sed -n 's/.*MAC Address : \([0-9a-fA-F:]*\).*/\1/p'` if there may be text after the match which should not be printed. – tripleee Oct 09 '20 at 09:40
  • 1
    @tripleee That is all good, just note the answer is meant to address the immediate issue without forcing OP to change the tool set used. I myself do not need any alternative if I am used to a specific tool. In this case, I'd also use `grep` with `-P` since I am a regular Ubuntu Linux user and an NFA regex fan. If OP were interested in `sed` solution, I'd have added it to the answer. – Wiktor Stribiżew Oct 09 '20 at 10:22
  • 2
    Sure, just commenting for future visitors. Perhaps this should be closed as a duplicate of an existing question anyhow, where then hopefully portability of answers would be at least broadly documented. – tripleee Oct 09 '20 at 10:27