On 1/17/06, Todd Walton <[EMAIL PROTECTED]> wrote:
> I want to use sed to take a config file, find an option in the file
> and change its value, and to leave the file in place. I want a
> portable, scriptable way to do 'vi settings.config', find setting,
> edit text, ":wq".
>
> I don't know sed at all, I just know that it does this kind of thing.
> What's the best way for a new person to approach getting a basic
> understanding of its use?
After writing the two examples below, I will start with general
advice: If you know how to use the : (command-line) mode of vi, you
already know how to write simple sed scripts. Just take the commands
you would use and put them into the script one line at a time. Note
that you can have more than one "find and replace" command in your sed
script, each will be attempted at every line of the input data file.
1) don't use sed to edit files in place. Even if GNU sed has the
option "-i" for this
It is much safer to do whatever changing you want from the source
file to a temporary destination file, and then rename the destination
file afterward.
2) if you are really only changing one line of the file, you can use
ed(1). A really simple-minded example follows. I have made an input
file named "text" and a script to edit it named "script".
- - - - - - - -
[EMAIL PROTECTED] edscript]$ cat text
one
two
three
four
[EMAIL PROTECTED] edscript]$ cat script
#!/bin/sh
/bin/ed - $* << end
g/two/s//TWO/
w
end
[EMAIL PROTECTED] edscript]$ chmod +x script
[EMAIL PROTECTED] edscript]$ ./script text
[EMAIL PROTECTED] edscript]$ cat text
one
TWO
three
four
- - - - - - - -
3) Doing this with an "ed" script means that the whole business of
making the changes into a temporary file and then renaming the
temporary file is hidden behind the curtain by the "ed" program.
Having done that for an example, maybe sed is easier.
- - - - - - - -
[EMAIL PROTECTED] edscript]$ cat script2
#!/bin/sed -f
s/two/TWO/
[EMAIL PROTECTED] edscript]$ chmod +x script2
[EMAIL PROTECTED] edscript]$ ./script2 < text > sed.out
[EMAIL PROTECTED] edscript]$ mv sed.out text
- - - - - - - -
Subtleties to be noted here: sed has the option "-f" which lets me use
#!/bin/sed -f
to mean "use the rest of this script as a command input to sed.
ed does not. So I have to use a shell "here document" to produce the
command input to ed.
Also, there is a whole lot more to sed than just find and replace, and
then we get into the philosophical question of whether to use a simple
scripting language for simple problems, or to try to use a more
complicated language.
carl
--
carl lowenstein marine physical lab u.c. san diego
[EMAIL PROTECTED]
--
[email protected]
http://www.kernel-panic.org/cgi-bin/mailman/listinfo/kplug-list