[Novalug] Command line search and replace tool - GNU sed?
Jon LaBadie
novalugml@jgcomp.com
Sun Sep 15 01:49:53 EDT 2013
On Sat, Sep 14, 2013 at 07:25:48PM -0700, John Christopher wrote:
> I need a command line tool that will search and replace in a text file, and will *not* do regexp translations.
>
> GNU sed does *almost* what I want:
>
> $ cat sedscript.txt
> s/FOO/\nBAR\n/g
>
> $ cat myfile.txt
> hello FOO world
>
> $ sed -f sedscript.txt myfile.txt
> hello
> BAR
> world
>
> In the example above, what I want is to have the following output:
>
> $ sed -f sedscript.txt myfile.txt
> hello \nBAR\n world
>
> I want to avoid having to change \n to \\n in sedscript.txt (it gets difficult to read).
>
> Is there a way to instruct sed to *not* translate regexp metacharacters (such as \n) and leave it as is?
Point of nomenclature: while the search pattern of a
sed substitute command is processed as a regular expression,
the replacement pattern is not.
The replacement pattern is processed for a few metacharacters.
Most of these involve a leading backslash eg. your '\n'.
The only replacement pattern metacharacter I can think of that
doesn't have a leading backslash is ampersand (&).
To avoid those ugly strings of backslashes in the "user code",
you might add them via a script. For example, assuming only
literals in the search pattern:
$ cat change.sh
sed -e "$(cat $1 | sed 's/\\/\\\\/g')" $2
$ change.sh sedscript.txt myfile.txt
Hello \nBAR\n world
> Is there another command line tool that will do ultra-simple search and replace and *not* do regexp translations?
>
> Thanks for your help.
I didn't know of one but a web search turned up "replace".
On Fedora, this command comes with the MySQl or MariaDB
packages.
$ replace FOO '\nBAR\n' < myfile.txt
Hello \nBAR\n world
or to change the actual file:
$ replace FOO '\nBAR\n' -- myfile.txt
myfile.txt converted
$ cat myfile.txt
Hello \nBAR\n world
Jon
--
Jon H. LaBadie novalugml@jgcomp.com
11226 South Shore Rd (703) 787-0688 (H)
Reston, VA 20190 (609) 477-8330 (C)
More information about the Novalug
mailing list