I have a Ruby script that calls ‘sed’ as so:
command = "sed -i \"s*#{find_what]}*#{replace_with}*\" #{file} "
system `#{command}`
When I have a replacement string that spans multiple lines it is not properly escaped and appears all on one line in the “file”.
What can I do to escape the string properly so sed replaces it with the line breaks intact?
Thanks
I presume your
replace_withcontains strings like this:You’ll need to escape the
\nfrom the Ruby interpreter and the shell interpreter so that they can be read bysed(1). Try this:The first doubling:
\\to\\\\is to get all the backslashes past Ruby. The second doubling:\to\\is to get a backslash past the shell.sedought to see only a single\.A simple test:
If you must use
sedfrom within a script, please use the array-based execution method as suggested by Ismael and pguardiario. See the hilarious Process Identifier Preservation Society website for detailed reasons why it is safer to avoid using the shell to start every new process. Better of course would just use the Ruby built-in support for replacement.