Re: executing command...



On 2006-04-27, M. Åhman wrote:
On Thu, 27 Apr 2006 15:23:51 -0400
"Chris F.A. Johnson" <cfajohnson@xxxxxxxxx> wrote:

On 2006-04-27, onlineviewer wrote:
Hello All,

How do you execute a command on a file rather than have it direct to
standard out.
I want to run this command: "sed '/string/G' file.log"
But rather than redirect the result to a new file or just the screen, i
want the file "file.log" that i am working on to get modified.

Recent versions of the GNU version of sec had an -i option which
changes the file. I don't recommend using it, however. The safe
method is to redirect output to a temporary file (or copy it, use
the copy, and redirect output to the original file), e.g.:

cp FILE tempfile
sed '....' tempfile > FILE


Actually, writing 'FILE' and 'tempfile' twice is time-consuming and
increase chance for errors.

Not at all. The time is the same (since that is what sed -i does
anyway), and the possibility of errors is reduced, as you have a
backup of your file.

Actually, both GNU sed and FreeBSD sed have the -i option, and both
have methods of creating backup files when using -i.

$ cat in-place
#!/bin/sh -e

file="$1"
shift
cp -fp "$file" "$file~"
eval "$@" < "$file~" > "$file"

$ in-place file.log sed '/string/G'

Magnus


--
Chris F.A. Johnson, author <http://cfaj.freeshell.org>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, is written for the POSIX locale
===== and is released under the GNU General Public Licence
.



Relevant Pages

  • Re: executing command...
    ... standard out. ... But rather than redirect the result to a new file or just the screen, ... method is to redirect output to a temporary file (or copy it, ... tempfile> FILE ...
    (comp.unix.shell)
  • Re: redirecting to screen and file (was: date +%u)
    ... is possible to redirect output on monitor and in the ... See: man tee ... Redirects the cmd's standard output. ... It makes it easier if you want to also redirect the standard ...
    (comp.unix.shell)
  • Re: executing command...
    ... standard out. ... But rather than redirect the result to a new file or just the screen, ... method is to redirect output to a temporary file (or copy it, ... cp FILE tempfile ...
    (comp.unix.shell)
  • Re: gfortran: cannot redirect output (errors and warnigns) )with > in ms-dos
    ... "Even if you redirect output to the NUL device, ... or by using the StdErr device. ...
    (comp.lang.fortran)