how can I make this sed capture accomplish a more complex substitution

when fixing mass spelling errors in my code base i have used this:

find . -path '*/.svn' -prune -o -name  "*min.js" -prune -o -name "*min.css" -prune -o -name "flashLocaleXml.xml" -prune -o -type f -print0 | xargs -0 egrep -n "priority=" -exec sed -i 's/replace/newval/' {} \;

to fix a specific spelling error in all the files in my repo.

however, i am not very good with sed captures, i want to do something like:

X.addEventListener(LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);
becomes:
EventUtil.addEventListener(X, LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);

I have read up extensively but I would appreciate someone explaining how sed captures work with this as a specific example.

I have given it a few shots, but nothing I come up with works: here are my tries

echo "X.addEventListener(LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);" | sed 's/\(.*\)EventUtil\(.*EventUtil\)/\1X\2/'

echo "X.addEventListener(LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);" | sed -r 's/(....),(....),(*\.addEventListener)(LevelUpEvent.*)/\1,\2\n\1,\2,/g' 

echo "X.addEventListener(LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);" | sed 's/\([\.$]*\) \([\.$]*\)/\2 \1/'

thank you in advance!

Upvotes: 2

Views: 399

Answers (3)

Rolf van de Krol
Rolf van de Krol

Reputation: 444

Try this

echo "X.addEventListener(LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);" | sed -e "s/\([A-Za-z]\{1,\}\)\.addEventListener(/EventUtil.addEventListener(\1, /"

This regexp will recognize a variable name using

\([A-Za-z]\{1,\}\)

Then .addEventListener(

\.addEventListener(

And replace it with

EventUtil.addEventListener(\1

In which \1 represents the variable name

Upvotes: 2

Birei
Birei

Reputation: 36272

Try with:

sed 's/\([^.]*\)\([^(]*(\)/EventUtil\2\1, /'

Output:

EventUtil.addEventListener(X, LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);

Explanation:

\([^.]*\)                  # Content until first '.'
\([^(]*(\)                 # Content until first '('
EventUtil\2\1,             # Literal 'EventUtil' plus grouped content in previous expression.

Upvotes: 3

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57670

This sed command will do.

sed 's/\(X\).\(addEventListener\)(\(LevelUpEvent.GENERIC_LEVEL_UP, updateLevels\));/EventUtil.\2(\1, \3);/'

Example

$ echo "X.addEventListener(LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);" | sed 's/\(X\).\(addEventListener\)(\(LevelUpEvent.GENERIC_LEVEL_UP, updateLevels\));/EventUtil.\2(\1, \3);/'
EventUtil.addEventListener(X, LevelUpEvent.GENERIC_LEVEL_UP, updateLevels);

Upvotes: 2

Related Questions