You don't need a regEx
type replacement while using sed
, just use the classic temporary string swap for replacement. (tmp=a;a=b;b=tmp;
), works on any instances of the pattern on each line, assuming for an input file like that. To make sure the the temporary random tmp
does not occur in your file, create a random string and assign it to tmp
variable
$ tmp="$(openssl rand -base64 32)"
$ tmp="${tmp//[^[:alnum:]]/}"
and stripping off any non-alphanumeric characters which could harm normal sed
operation.
$ cat file
This is a test file two and one two one two two two
test line again one two one two
last line one two two two
The sed
logic takes care of all replacements
sed "s/two/$tmp/g;s/one/two/g;s/$tmp/one/g" file
This is a test file one and two one two one one one
test line again two one two one
last line two one one one