Bash – Working with columns – awk and sed

awkbashsed

I am trying to parse a text file that is generated by an expec script that
pulls down some information from a switch.

Here is a sample output:

192      0000.0000.0000        1/g23      Dynamic              
192      0000.0000.0000        ch1        Dynamic              
192      0000.0000.0000        ch1        Dynamic              
192      0000.0000.0000        ch1        Dynamic

The text file has a lot of other junk in it that I am not interested in. I only want the lines that contain the switch number and the port – "1/g23" in the example above.

I did a grep on the file to extract the lines that contain the pattern '/g'
and it works great.

Now all I want are the two middle columns.
I used awk to print the columns.

0000.0000.0000 1/g23

Now that that is done I want to get ride of the '.'
sed worked okay for this

000000000000 1/g23

From here I want to convert only the first column to a MAC address format.

So this
000000000000 1/g23
Becomes this
00:00:00:00:00:00 1/g23

I was able to find a sed command that would accomplish this. But my problem is I only need it done on the first column. I am not quite sure how I can edit only the one column and not lose the association between the MAC and the port.

grep -e "/g" switch6output | awk '{print $2,$3}' | sed 's/\.//g' | sed 's/../&:/g;s/:$//'

I'm sure this is a really stupid way of doing it, but it was the best I could come up with. Is there a more reliable way I can accomplish what I need without losing the MAC and port association?

Thank you.

Best Answer

Just use awk directly:

awk '/\/g/ {
        gsub(/\./, "", $2)
        gsub(/../, "&:", $2)
        sub(/:$/, "", $2) 
        print $2,$3
}'

With this solution you don't need grep nor sed.

Related Question