Charles
Charles

Reputation: 11778

Why is sed adding a new line to the file and how to prevent it?

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.

Upvotes: 2

Views: 497

Answers (2)

Simon PA
Simon PA

Reputation: 746

You can use this, or combine with pipe:

truncate -s -1 <file>

(this remove the last byte of the file )

Upvotes: 0

Camusensei
Camusensei

Reputation: 1563

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.

Upvotes: 1

Related Questions