2

I have this requirement where show mac address table of a switch will list 1000 entries .

file1:

switch_1#show mac address table
AA:AA:AA:AA:AA:AA port 47
BB:BB:BB:BB:BB:BB port 48
.
.
.
DD:DD:DD:DD:DD:DD port 50
file2:

switch_2#show mac address table
AA:AA:AA:AA:AA:AA port 47
BB:BB:BB:BB:BB:BB port 48
.
.
.
DD:DD:DD:DD:DD:DD port 45

I need to find a way to display the line containing DD:DD:DD:DD:DD:DD and once this occurs, it should search few lines above and print the hostname containing line as well

So the output should look like:

switch_1#show mac address table
DD:DD:DD:DD:DD:DD port 50
switch_2#show mac address table
DD:DD:DD:DD:DD:DD port 45

file1, file2are stored in the same directory (these are just examples, there is like 100+ files/switches and MAC needs to be filtered along with the switch names)

3

awk solution

If we get a line with a hash, store it in variable a.

If we get a line with a matching MAC address, print variable a, along with the current line.

$ awk '/#/{a=$0}/^DD:DD:DD:DD:DD:DD/{print a"\n"$0}' file1 file2
switch_1#show mac address table
DD:DD:DD:DD:DD:DD port 50
switch_2#show mac address table
DD:DD:DD:DD:DD:DD port 45
$

sed solution

If we get a line with a hash, place it in the hold space (h).

If we get a line with a matching MAC address, append to the pattern space (H), copy hold space to pattern space (g), print pattern space (p)

$ sed -n '/#/h;/^DD:DD:DD:DD:DD:DD/{H;g;p}' file1 file2
switch_1#show mac address table
DD:DD:DD:DD:DD:DD port 50
switch_2#show mac address table
DD:DD:DD:DD:DD:DD port 45
$
  • 1
    or sed '/😀/h;/😩/!d;H;x if you're a golfer... – don_crissti Aug 8 '18 at 22:36
  • is it possible to print one line next to the matching regexp in the awk solution? meaning, If we get a line with a hash, store it in variable a, If we get a line with a matching MAC address, print variable a, along with the current line and the immediate next line. – Maran Ganesh Jan 17 at 17:27
  • Maran - that probably warrants an entirely new question, with new examples of input/output. – steve Jan 19 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.