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)

0

1 Answer 1

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
$
3
  • 1
    or sed '/😀/h;/😩/!d;H;x if you're a golfer... Commented Aug 8, 2018 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. Commented Jan 17, 2019 at 17:27
  • Maran - that probably warrants an entirely new question, with new examples of input/output.
    – steve
    Commented Jan 19, 2019 at 15:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .