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
    What permissions do you want the new file to have? You're trying to use `sudo ... > file`, but [that won't create/write the new file with sudo permissions](https://unix.stackexchange.com/questions/1416/redirecting-stdout-to-a-file-you-dont-have-write-permission-on). – JigglyNaga Feb 05 '20 at 10:31
  • How come `echo > test.txt` does not preserve permissions? `touch test.txt; chmod 200 test.txt; echo >test.txt; ls -l test.txt` => `--w-------` –  Feb 05 '20 at 10:32
  • "My intention is to write to a new file which at all times has the correct permissions." - Then don't change the permissions. – lainatnavi Feb 05 '20 at 14:43
  • 1
    Note that the redirection is not done as root in your last example, but by whoever is running the current interactive shell. – Kusalananda Feb 05 '20 at 14:54

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