Sometimes simplest things take your time in shell scripting like crazy.
Content='me \n you \n him \n'
echo $Content > Names.txt
When I open the Names.txt
it has two empty lines at the end.
I want it to only have one empty line. The Content
variable is calculated in a loop and in each iteration it adds a new line to it. Thus I can't change Content
.
I can't use echo -n
because it removes all new lines.
I can't remove the \n
from my loop, because in that case all lines are concatenated to each other.
I tried Content=$(echo $Content | awk 'NR>1{print PREV} {PREV=$0} END{printf("%s",$0)}')
to use awk
to remove the trailing newline, but it does not work. I took it from an answer on this site.
I tried to use printf %s $Content > File.txt
instead of echo -e
, still no success.
How can I either remove the trailing newline from a given string variable or write it as is to the file and tell Linux not to append yet another line to it?
Content='me \n you \n him \n'
and runecho -e "$Content"
(or any echo that interprets backslash-escapes, like Bash withxpg_echo
set, or the implementations in many other shells), the resulting output will end inhim
, a space and two newlines. The first newline terminates the line with the wordhim
, so there'll be one empty line at the end, not two. – ilkkachu Jun 30 '22 at 17:22n
. – ilkkachu Jun 30 '22 at 17:25printf
? Note that they've tagged this with Bash, but in a lot of systems, their shown code doesn't even work in Bash, since its defaultecho
doesn't process backslash-escapes... (i.e. as far as I've seen,xpg_echo
isn't on by default in many distributions) – ilkkachu Jul 01 '22 at 08:24bash
; could you verify it's bash? What happens when youecho $SHELL
? What happens when you runecho $0
? – Marcus Müller Jul 01 '22 at 09:09