LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   pipes and streams and one file (https://www.linuxquestions.org/questions/linux-newbie-8/pipes-and-streams-and-one-file-681782/)

viroos 11-07-2008 09:40 AM

pipes and streams and one file
 
Hi,
I'm writing little Sed wrapper. It's task is to replace text. I have to override original file.

so my first try was:
Code:

#!/bin/bash
sed s/$1/$2/g <$3 >$3

and i got empty file. Hire is my first question: why for commend like this:
Code:

./my_script foo bar file
and file like this
Code:

foo
foo
foo

file is empty instead of one "bar" word?

Anyway I fixed this with:
Code:

#!/bin/bash
sed s/$1/$2/g <$3|cat >$3

And It works! But I'm not sure why? I think I should get only one bar word because when first line is outputted the input file is maked.

The second approach works but maybe I should better use tmp file?

Sorry for my poor English. And TIA for answers.

estabroo 11-07-2008 09:52 AM

yes it's better to use a temp file in this case. when you use > it wipes the file you are writing to and since you were reading and writing from the same file the contents were getting wiped before you did anything with them. The pipe to cat only worked because the file was small. If it had been larger than one buffered read I'd bet you see similar problems to your first attempt.

Tinkster 11-07-2008 12:56 PM

And in addition to the temp-files idea:

newer GNU seds (> 3) allow in-file changes.

Code:

sed -i.bak s/$1/$2/g $3
with an optional back-up file created.


Cheers,
Tink


All times are GMT -5. The time now is 12:02 AM.