0

When creating a new empty file, how do I then add a newline to it?

Running these commands:

$ touch test.txt
$ sed -i '$a\' test.txt
$ sed -i '1s/^/\n/' test.txt
$ wc -c test.txt
0 test.txt

it is clear sed had no effect.

My intention is to write to a new file which at all times has the correct permissions. Following this answer an empty file is created, but I'm having trouble editing the file non-interactively.

Using echo is not desirable, because it does not preserve permissions, as seen in this example:

$ sudo echo "text" > test.txt
$ stat -c "%U:%G" test.txt
me:mygroup

1 Answers1

0

These commands worked for me:

touch test.txt
stat  test.txt
cat test.txt
echo "" >>test.txt
cat test.txt
stat  test.txt

If you do

echo " " > test.txt

It will create a new file from scratch, need to use >> to append the CR.

Maybe that was causing your problem.

  • 1
    Using > to an existing file will not recreate the file, i.e. it will not delete the file and create a new file. It will however truncate the contents of the file. Any meta data associated with the file (permission and ownership) will not be altered. – Kusalananda Feb 05 '20 at 14:53