2

How can I prevent sed from adding a new line at the end of the file using this command:

find . -not -path "./.git/*" -type f -name '*' -exec sed -i '' 's/password1/passworddeleted/g; s/password2/passworddeleted/g;' {} +

EDIT: To prove my question:

mkdir test; cd test; printf "no new lines" > no-new-line.txt; cat -e no-new-line.txt; find . -not -path "./.git/*" -type f -name '*' -exec sed -i '' 's/password1/passworddeleted/g; s/password2/passworddeleted/g;' {} +; cat -e no-new-line.txt;

Will output no new linesno new lines$. cat -e displays non-printing characters on mac.

Charles
  • 11,367
  • 10
  • 77
  • 114
  • This is not adding any new line to me. What OS are you running this on? Try providing a [mcve] as well. – fedorqui Apr 18 '16 at 10:07
  • I added an example. Thanks for pointing it to me. – Charles Apr 18 '16 at 11:14
  • Interesting. In CentOS I do not get any new line. Funny thing I asked something similar about new lines being or not being added by programs, and `sed` apparently does not. See it in [Trailing new line after piping to a command: is there any standard?](http://stackoverflow.com/q/36641445/1983854). – fedorqui Apr 18 '16 at 11:20
  • 3
    A file without a terminating newline is not a text file and so you should not expect a text-processing tool like sed or awk or grep or... to be able to handle it in any particular way. See [why-should-text-files-end-with-a-newline](http://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline). – Ed Morton Apr 18 '16 at 13:57
  • @EdMorton A text file may have 0 lines, hence can not be defined in terms of newline. http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_397. – SLePort Apr 18 '16 at 14:37
  • @Kenavoz we're getting bit lawer-y now but fine `s/A file/A non-empty file/` or however you feel it should be stated. – Ed Morton Apr 18 '16 at 14:41
  • @EdMorton Interesting link anyway. – SLePort Apr 18 '16 at 14:46

2 Answers2

1

sed always ends its output by a newline character and you cannot force it to do otherwise.

From POSIX man sed:

Whenever the pattern space is written to standard output or a named file, sed shall immediately follow it with a newline.

As an alternative, you can use something else than sed or strip the last character of sed's output.

Camusensei
  • 1,475
  • 12
  • 20
0

You can use this, or combine with pipe:

truncate -s -1 <file>

(this remove the last byte of the file )

Simon PA
  • 748
  • 13
  • 26