bashtac

Bash script shows changes in console but not in file | How do i save changes?


New to Bash scripting.

I have a textfile bar.txt with text:

123
456
789

I am trying to reverse this to:

987
654
321

I have managed to do this just fine with:

tac bar.txt | rev

However, the changes doesn't save to the .txt file, which still has 1234...

How do i save the changes, so that the .txt file is updated? Sorry for badly phrased question or bad formatting - new to both Bash scripting and stackoverflow...


Solution

  • True to the Unix philosophy of using shell utilities as filters operating on text, both tac and rev are piping their output to standard output, which is how rev is able to operate on the output from tac.

    To "update the file," you can redirect the resulting output from rev to another file, like this.

    tac bar.txt | rev > foo.txt
    

    The reason you don't want to redirect the output to the same file is because Unix pipes operate on inputs as they are ready, so foo.txt will likely not have been completely read by the time the output from rev is ready to be written to the file.

    You could just append the output, of course, like this:

    tac bar.txt | rev >> foo.txt
    

    This would append the output, though, not actually "update" the file.

    If you wanted to actually "update the file", you could write a script that processed your input, piped it to a temporary file, and then replaced the original file with the new file using something like the mv -f command.

    The reason I keep using the phrase "update the file" in quotation marks is because this process of creating a temporary file or memory buffer with the updated contents of the file that then replace the original file is usually what is happening when you "update a file." If you've ever seen the temporary files with the ~ symbol that vim creates, that's the temporary buffer that you're editing before the original file gets replaced, or as most people call it, "gets updated."