What is the best way to search and replace strings in a file?

Hi,

In my CMake script, I need to modify other source files by searching and replacing specified strings. In my case, the configure_file command is not a solution because I have no control over the input file. Previously I used the file and string commands in the following way -

file(READ header.h FILE_CONTENTS)
string(REPLACE "old text" "new text" FILE_CONTENTS ${FILE_CONTENTS})
file(WRITE header.h ${FILE_CONTENTS})

However this technique appears to strip out semi-colons from the input file.

What is the best way to search and replace strings in a file?

1 Like

Try putting quotes around ${FILE_CONTENTS} in both commands where you use that.

1 Like

Thanks Craig, quoting the variable references worked perfectly! I searched for this feature on https://cmake.org/cmake/help/latest/ but found nothing. Do you where/if this behaviour is documented?

It comes from a CMake’s list syntax, which is ;-separated, the fact that arguments passed to CMake commands are basically mashed together into a list, and that those commands take unbounded number of inputs. So you end up with one longer list. Quoting prevents the semicolons in the expansion from being treated as list-element-separators.
Think:
WRITE;header.h;x;y;z
vs
WRITE;header.h;"x;y;z"

1 Like