[YLUG] How do to substition in a file with sed or similar

Zoe Stephenson zrs1 at york.ac.uk
Fri Oct 27 12:47:49 BST 2006


On Fri, Oct 27, 2006 at 11:47:56AM +0100, Robert Hulme wrote:
> Hi list,
> 
> I know I can:
> sed s/foo/bar/ myfile
> 
> which dumps to stdout
> 
> How I do the substition on the file 'in place'?
> 
> sed s/foo/bar/ myfile > myfile
> 
> Results in a zero length file (which I'd kinda expect from the stream editor).
> 
> Do I need to use a temporary file or is there some kind of buffer I could use:
> sed s/foo/bar/ myfile | streambuffer > myfile
> 
> Or is there a magic switch or should I be using something other than sed?

As you correctly surmise, sed isn't really intended to edit in place.
ed, however, certainly is.  A really simple demonstration, hope it
comes through OK:

#!/bin/sh
file="foofile"
>"${file}" cat <<..E
A file
---
A file
---
A file
..E
>/dev/null 2>&1 ed "${file}" <<..E
/^--/;
.,/^--/s/A/B/
w
q
..E

The commands in the input to ed tell it to search for ^--, then
anywhere from there to the next ^-- replace the first A on a line with
B.  Don't forget the w, and the q is just polite.  I think this is
probably the most sed-like solution there is without actually using
sed.

-- 
 -- zoe



More information about the York mailing list