Replace strings with text with GNU ed

905 views Asked by At

I want to replace %foo% (found in file test) with a string containing every possible character. Because of the missing character limitation, the following is not possible (executed in BASHv4):

echo %foo% > test
replacement="//this//is//a//test"
ed -s test <<< "g/%foo%/s/%foo%/$replacement"

Any idea how to replace %foo% with every possible text?

2

There are 2 answers

0
Rayne On BEST ANSWER

With command r it is possible to load text from another file, so the following is a valid solution:

  • store replacement to another file
  • open file with ed
  • move pointer to location
  • delete line (fake replace follows)
  • load text from file with r FILE
  • write and quit
0
themel On

I'll warrant the guess that you will get pretty close to your goal by escaping slashes and backslashes with a prepended backslash each. AFAIK that can't be done in bash in a single step, so you can either write a function to make it readable, or enjoy your trip to the leaning toothpick forest:

$ echo %foo% > test
$ replacement="//this//is//a\\\\//test"
$ echo $replacement
//this//is//a\\//test
$ stage1=${replacement//\\/\\\\}
$ echo $stage1
//this//is//a\\\\//test
$ stage2=${stage1//\//\\\/}
$ echo $stage2
\/\/this\/\/is\/\/a\\\\\/\/test
$ ed -s test <<< g/.*foo.*/s/foo/$stage2/p
%//this//is//a\\//test%

Newlines remain a problem, but then you don't want to keep them in bash environment variables anyway since whitespace isnt' very stable there.