Reputation: 815
I have this function that works like this
Add(1,2);
Add(3,4);
And need to replace with this
Add({num1 : 1, num2 : 2});
Add({num1 : 3, num2 : 4});
This happens in hundreds of places across multiple files so I want to write a script that can do this for me.
Using regex I can find the places where this happens
/Add\(.*\);/
But I'm not sure how to replace the inside of the function call with what I need.
I'm not sure also what the best langauge to use to write the script. I was going to use JavasScript to write it in node but would use Bash with sed if there is an easy solution there.
Upvotes: 2
Views: 1065
Reputation: 15461
This should work for you :
sed -i 's/Add(\([0-9]*\),\([0-9]*\))/Add({num1 : \1, num2 : \2})/' file
The -i
option is for editing the file in place.
Upvotes: 0
Reputation: 5092
Try this sed method
sed 's/\([^(]\+.\)\([^,]\+.\)\([^)]\+\)\(.*\)/\1{num1 : \2,num2 : \3}\4/g' FileName
Upvotes: 0
Reputation: 386680
You could use replace with an appropriate string.
var regex= /(Add\()(\d+),(\d+)(\))/g,
replace = '$1{num1: $2, num2: $3}$4'
console.log('Add(3,4);'.replace(regex, replace));
Upvotes: 2
Reputation: 671
I would go with:
perl -i -pe 's/Add\((\d+),(\d+)\)/Add({num1 : $1, num2 : $2})/' filename
Regarding your regular expression, it's not complete, and /Add\((\d+),(\d+)\)/
will take care of catching the instruction and capturing the first and second numbers into $1
and $2
, respectively.
The flags work as follows:
-i
does in-place edit (this will rewrite your file; if you're not comfortable with that either remove the flag to look at the output or use -i.bak
to create a backup of your file-p
parses each line and prints it in the end-e
(from "eval") is what allows you to run a one-liner instead of a scriptUpvotes: 1