sed not working

hello,

I am not able to redirect the output to the same file, where I am searching and replacing a pattern.

D:\>cat abc.txt
abc
D:\>sed "s\abc\xyz\g" abc.txt > abc.txt

D:\>cat abc.txt

D:\>

If I dont redirect the output to abc.txt, the command is working fine, even if I append the output to the file, it works. but I want to replace the string in the same file.

Please help.

thanks,
chetan

use the -i option if you are using GNU sed. also your syntax is wrong. I will let somebody else show you.

$ ruby -i.bak -ne '$_.gsub!(/abc/,"xyz")' myfile

hey thanks dude, but I am not really able to get what you have written (dont mind). I am new to shell environment.

The command is working fine for stdout -

D:\>cat abc.txt

D:\>cat abc.txt
abc
D:\>sed "s\abc\xyz\g" abc.txt
xyz

D:\>sed "s\abc\xyz\g" abc.txt > abc.txt

It is not redirecting the output to abc.txt.

OK, so I am that "somebody else"~
You can't redirect your output to the original input file, that would just wipe out the whole file. you can use the i option to replace text in place.

sed -i 's/abc/xyz/g' abc.txt

man sed for more info.

Hi Kevin,

sorry for the trouble. I had tried -i option, but it is not available

D:\>sed -i 's\abc\xyz\g' abc.txt
sed: Unknown option -i
Usage: sed [-n] script [file...]
       sed [-nE] [-e script] [-f scriptfile] [file...]

D:\>help sed
sed -- stream editor (non-interactive)
Usage:  sed [-En] script [file ...]
        sed [-En] [-e script]... [-f scriptfile]... [file ...]

-E              use extended regular expressions
-e script       add argument "script" to end of script
-n              suppress output except from commands in sed script
-f scriptfile   add commands in "scriptfile" to script

Hi.

Then you should write it to a temporary file, then copy it back over the original.

sed "....." abc.txt > abc.tmp
move abc.tmp abc.txt

Thanks a lot for your guidance :slight_smile:

Oh, that's bad.
Anyway you can still do what scottn suggested.

There's also ed and ex. Just about every single time you see code that uses gnu sed's -i extension, it's something that can be easily done with the ubiquitous, standardized line editors.

Regards,
Alister

P.S. Woohoo ... 1,000th post. :wink:

D:\> tells me that the OP might not have "ubiquitous, standardized line editors" :slight_smile:

Well done.

And, what better a time to use posh words than your 1000th post? :smiley:

Heheh. True. But if sed is available, perhaps there's hope.

Keeping hope alive,
Alister