Looking for literal strings with a regular expression, when the search-string contains special characters, is sometimes not as simple as looking for patterns, but you can do it with a bit of juggling.
Note: The echo
command must cater for CMD-special-characters, so it needs ^^
to escape a single ^
and ^|
to escape |
... You don't need CMD's escape-character ^
if you type directly into the file.
Step 1: Create a file, named literal-srch-strings.txt, which containing the exact (unaltered) string to be replaced. There are 2 ways to create this file:
As a command issued at CMD's commandline, or as a command in a .cmd/.bat command-script.
echo sed -i^^/\\*$/$[{" ;"> literal-srch-strings.txt
Make literal-srch-strings.txt yourself, in your text editor.
In this case, you should not use the CMD-escape-character ^
, so the line is has just one ^
, not ^^
-- This is because you are bypassing the CMD-shell.
Here is what is needed in the .txt file (just as the filename says :)
sed -i^/\\*$/$[{" ;"
Step 2: Make a sed script, named str-to-regex.sed , to convert the string(s) into sed regex(s).
Note that the same issue of the CMD-escape-character ^
applies to this step, so again, there are 2 ways you can create the .sed file:
As a command:
echo s/[]\/$*.^^^|[]/\\^&/g; s/.*/s\/^&\/Ciao!\/g/> str-to-regex.sed
Using your text editor, make a file named str-to-regex.sed, containing:
s/[]\/$*.^|[]/\\&/g; s/.*/s\/&\/Ciao!\/g/
Step 3: Run the sed-script which converts the string into a sed regeular expression, and
send its output to another sed-script, replace-text.sed, which will make the actual replacement.
sed -f str-to-regex.sed literal-srch-strings.txt > replace-text.sed
Step 4: Run replace-text.sed -- For the test we can use literal-srch-strings.txt as the input file, but you can, of course, use any input file.
sed -f replace-text.sed literal-srch-strings.txt
Here is the output:
Ciao!
Addresses in sed
can be either line numbers or patterns. Try this:
sed -n '/16:30/,$p'
If the pattern contains a /
, you can escape it with a \
. For example, to search for 16/30
instead of 16:30
, try this:
sed -n '/16\/30/,$p'
Best Answer
There are two stages: first you need to escape any special characters in
$ip
:Then you need to perform the substitution:
Together these give:
Note that the double quotes for the main substitution are important, so that the replacement string will be interpreted.