2

I am working on a bash script and running into a problem with sed leaving the file that I am using it to clean blank.

Here is the blocks that define the file and the function that I created to clean the file:

# Define Review Log file
reviewlog=/home/serverreview-$(date +%d%^b%y).txt
# Bleachs the Review Log of the color customization
bleach ()
{
sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" $reviewlog >> $reviewlog
}

Using the >> it does append the info to the bottom of the file as it is supposed to. However if I use:

bleach ()
{
sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" $reviewlog > $reviewlog
}

It leaves the output file totally blank

Rob Hood
  • 49
  • 1
  • 5
  • below is correct. Now, eliminate another whole class of errors from your shell scripting by always dbl-quoting variable references, i.e. `"$reviewing"` (except for a very few advanced cases) when using `set -- $@` for example. Good presentation of your Q, keep posting. Good luck to all. – shellter Jul 23 '16 at 02:15

1 Answers1

1

This is normal as sed reads as it writes. The first write will truncate the file. This ends reading and leaves an empty file.

In some condition when a tool reads a buffer before writing it would work for small inputs. But this is nothing you dont want to depend on. so if the tool does not have a in-place overwrite option don't use it.

You can write to a temp outfile and rename it over the infile or rename the in-file (or open the in-file, then delete it) and then write to the expected location. Otherwise you have to ensure to read everything into memory.

sed -i with and without extension does work the same. See for example https://robots.thoughtbot.com/sed-102-replace-in-place which describes the -i variations.

eckes
  • 10,103
  • 1
  • 59
  • 71