tags:

views:

147

answers:

1

I have a really long port map where I want to replace a bunch of

SignalName[i],

with

.SignalName(SignalName[i]),

I think I can do this easily with regular expressions, but I can't for the life of me figure out how. Any ideas?

+2  A: 

Assuming SignalData is the file containing your port map information, the following would do what you want.

sed -si 's/\([a-zA-Z]\+\)\(\[[^\]]*\]\)/\.\1(\1\2)/g' SignalData

In sed s stands for substitution, regex between the first pair of // is used to match against each line. If a match is found the expression between upto the next / is made to replace what was matched.

Explanation of regex

\([a-zA-Z]\+\) - Matches a series of alphabets (like SignalName) and captures it into
\1. If you want only the SignalName string to match, replace [a-zA-Z]\+ with SignalName.
\(\[[^\]]*\]\) - Matches the [some character] part and captures it into \2

Finally we use these captured strings to construct the desired string.

If you want to experiment with this before running on your file use sed -s instead of sed -si. That will show the results of the transformation on stdout, without actually changing the file

Jasmeet
Used it in vim and it worked beautifully! Regular Expressions are really like magic. Thanks!
Adam