Page 1 of 1

ECHOing to a file without a trailing space

Posted: 10 Nov 2023 11:27
by miskox
Hello all!

Code: Select all

@echo off
set field1=a
set field2=(a
set field3=2
set field4=34564119

echo %field1%;%field2%;%field3%>file1.tmp
echo %field1%;%field2%;%field3%>file2.tmp
echo %field1%;%field2%;%field3% >file3.tmp
echo (%field1%;%field2%;%field3%;%field4%)>file4.tmp
Results:

file1.tmp and file2.tmp are empty because "2" redirects it.

file3.tmp (size 9 bytes - trailing space after number 2)

Code: Select all

a;(a;2 
file4.tmp (size 19 bytes)

Code: Select all

(a;(a;2;34564119)
You see that

Code: Select all

>>file.tmp (echo...)
is no good because my data can contain round brackets ().

I don't need a space at the end of the line.

I need:

Code: Select all

a;(a;2
(numbers 2 and are just to show different behavior. There is only one number at the end of the file)

Please help.
Thanks.
Saso

Re: ECHOing to a file without a trailing space

Posted: 10 Nov 2023 12:36
by jeb

Code: Select all

(echo(%field1%;%field2%;%field3%;%field4%)>file4.tmp

Re: ECHOing to a file without a trailing space

Posted: 10 Nov 2023 15:31
by OJBakker
Place the redirect before the echo to avoid the trailing space in the echo command.

Code: Select all

>file0.tmp echo %field1%;%field2%;%field3%

Re: ECHOing to a file without a trailing space

Posted: 11 Nov 2023 07:04
by Batcher

Code: Select all

>file4.txt echo %field1%;%field2%;%field3%
echo>file5.txt %field1%;%field2%;%field3%

Re: ECHOing to a file without a trailing space

Posted: 11 Nov 2023 09:35
by miskox
@jeb: your solution does not work. I have ( and ) in my data so I get

Code: Select all

34567891) was unexpected at this time.
@batcher: your solution:

Code: Select all

echo>file5.txt %field1%;%field2%;%field3%
works.

Thanks.
Saso

Re: ECHOing to a file without a trailing space

Posted: 12 Nov 2023 17:15
by mataha
Should be resilient enough:

Code: Select all

@setlocal DisableDelayedExpansion
@set field1=a
@set field2=(a
@set field3=2
@set field4=34564119
@setlocal EnableDelayedExpansion

@for /f delims^= %%s in ("(!field1!;!field2!;!field3!;!field4!)") do @(echo(%%s) >"file4.tmp"

Re: ECHOing to a file without a trailing space

Posted: 13 Nov 2023 04:59
by jeb
With DelayedExpansion it's safe with all character, but then you don't need the FOR /F

Code: Select all

@echo off
setlocal DisableDelayedExpansion
set field1=a
set field2=(a
set field3=2
set field4=34564119
setlocal EnableDelayedExpansion

(echo(!field1!;!field2!;!field3!;!field4!) >"file4.tmp"