This question already has answers here:
Closed 2 years ago.
How can I replace all occurrences of
check_free_set_to_null(&pointer)
by
if (pointer)
{
free(pointer)
printf(pointer have been freed)
}
else
{
printf(pointer couldnt had been freed)
return (1)
}
// maybe using some sort of
{1} = check_free_set_to_null(CONTENT)
if ({1})
{
free({1})
printf({1} have been freed)
}
else
{
printf({1} couldnt had been freed)
return (1)
}
how could I do that ? (take note thats its not exactly what that have to be replaced, its just an example) Im not looking for the compiler to interpret it as multiple line, im looking for modifying the file.
Basically exactly how you said, except...
This is one of those questions where the right answer is probably "Here's how to do the stupid thing you're asking to do, but PLEASE REALLY PLEASE tell us what your real problem is, that you're trying to solve, because this almost certainly isn't the right way to do it."
First, the search string should be (this is for vim, because I see the tag vim. If you want to do it using some other replacement regex thing, let us know which. Perl, php, sed, awk, the bash commandline, something?):
:%s/\bcheck_free_set_to_null\(([^()]+)\)/ replacement text goes here /g
That presumes (possibly incorrectly) that there are never any braces inside the function - if that might be the case, then you are venturing into recursive regular expression territory, and in that case, you are definitely, definitely doing the wrong thing.
Your replacement string should be whatever your method will contain - in your example, it'd be:
:%s/\bcheck_free_set_to_null(\([^()]+\))/if (\1)\n{\n free(\1)\n printf("freed")\n}\nelse\n{\n printf("could not free")\n return (\1)\n}/g
Here we're using \n for line endings, because you're using vi, so you're probably on some kind of unix, and that's how they have their line endings.
Now, there's one thing we could improve here. Indentation.
:%s/\(\s+\)\(.*\)\bcheck_free_set_to_null(\([^()]+\))/\1\2if (\3)\n\1{\n\1 free(\3)\n\1 printf("freed")\n\1}\nelse\n{\n\1 printf("could not free")\n\1 return (\3)\n\1}/g
Here I grab the indentation into \1
, everything else on the line into \2
, and the method parameter into \3
. Which might let you make it a bit prettier.
But again: whatever you're trying to do here is probably the wrong thing to do. Tell us what the REAL problem is! Don't fix it this way! This way is BAD! THIS WAY HAS WEASELS AND ROACHES IN IT! AND THE WEASELS WON'T EVEN EAT THE ROACHES FOR YOU!