user2699113
user2699113

Reputation: 4509

sed and parsing MAC address

I'm trying to parse MAC address with sed but I faced something which I cannot explain.

Here there are 2 examples - good and wrong:

good one:

# echo "01:23:45:67:89:ab" | sed  -r 's/^([^:]{2}):([^:]{2}):([^:]{2}):([^:]{2}):([^:]{2}):([^:]{2})$/\1_\2_\3_\4_\5_\6/'
01_23_45_67_89_ab

wrong one:

# echo "tadam" | sed  -r 's/^([^:]{2}):([^:]{2}):([^:]{2}):([^:]{2}):([^:]{2}):([^:]{2})$/\1_\2_\3_\4_\5_\6/'
tadam

The first example is working fine - it returns parsed properly string. But how to explain the second one? Why sed is returning any string (tadam) while this string doesn't match te regexp?

Anyone can explain it? I'd like to achieve the situation where sed is returning nothing when the regexp is not matching the string. How to do it?

Upvotes: 2

Views: 913

Answers (1)

Cyrus
Cyrus

Reputation: 88756

sed's default setting is to print the complete pattern space.

Add option -n (suppress printing of pattern space) and add command p (print current pattern space):

echo "..." | sed -r -n 's/.../.../p'

Now sed only prints the pattern space if something could be replaced.

Upvotes: 2

Related Questions