0

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.