Myfile")"> Myfile")">
Ad

How To Redirect And Replace The Input File With The Output (don't Erase Myfile When Doing "cat Myfile > Myfile")

- 1 answer

What is the right way to redirect to a file used as input and replace the file instead of erasing the file? I want to do something like:

cat myfile > myfile

where the program (i.e., cat) reads the file and then redirects to the file, so in the example above myfile would be unchanged.

I know that the example above will erase the file, as explained here.

What is the proper syntax so the file will be replaced instead of erased? Is stdout and redirection possible, or should the program handle opening and writing the new data to the file? I would like to let my program send output to stdout and then the user can redirect or pipe or whatever.

BTW, I don't want to >> (concatenate). I want the function on the left to write "new" data to the file -- to replace the file contents.

Perhaps a better way to state it is that I want the left side of the redirection to fully occur before the streaming occurs -- is this possible? Do I have a fundamental misunderstanding of bash?

Ad

Answer

You have to either read all the data to memory first, or write to a temporary file and swap it out.

To read it into memory (like vim, ed and other editors do):

contents=$(<myfile)
cat <<< "$contents" > myfile

To create a temporary file (like sed -i, rsync and other updating tools do):

tmpfile=$(mktemp fooXXXXXX)
cat myfile > "$tmpfile" && mv "$tmpfile" myfile
Ad
source: stackoverflow.com
Ad