Page 1 of 1

avoid trailing space when piping to CLIP [SOLVED]

Posted: 22 Aug 2023 23:05
by green
Hi guys. Recently faced an issue with CLIP in Windows 7. When trying to send to it a text line without newline at the end, it appends the line with one space. How it possible to store in the clipboard just a line I want, without that stray space?

Code: Select all

SET/P=TEXT<NUL|CLIP
Execute this line, and you'll get not TEXT but TEXT  in the clipboard.

Re: avoid trailing space when piping to CLIP

Posted: 23 Aug 2023 01:07
by OJBakker
Use double quotes in the set command:
SET/P "=TEXT" <nul | CLIP

Re: avoid trailing space when piping to CLIP

Posted: 23 Aug 2023 01:35
by green
Magic! But how? :shock: I can't understand the difference. In my example there is NO ANY space, so I thought that the stray space is generated by CLIP, but not by my command. Could anybody explain to me where the stray space in my example comes from?

Re: avoid trailing space when piping to CLIP

Posted: 23 Aug 2023 02:12
by ShadowThief
The interpreter moves things around before it gets executed, so the line that actually gets run is

Code: Select all

SET/P=TEXT 0<NUL  | CLIP
You can see this by running your line by itself in a script with no @echo off

Re: avoid trailing space when piping to CLIP

Posted: 23 Aug 2023 02:27
by jeb
The extra space is indirectly generated by the pipe operation.

To use the pipe, cmd.exe converts the expressions on both sides.
Obviously this is hard to debug, but with the magic cmdcmdline variable it can be done.

Code: Select all

@echo off

(
  echo This is
  echo a test
  echo  %%cmdcmdline%%
  <nul set /p .=Output) | findstr /n "^"
output wrote: 1:This is
2:a test
3: C:\Windows\system32\cmd.exe /S /D /c" ( echo This is & echo a test & echo %cmdcmdline% & set /p .=Output 0<nul )"
4:Output
In line 3 you can see how cmd.exe convert and modify the code block to a one liner and the there is also the additional space in the set /p expression

Re: avoid trailing space when piping to CLIP

Posted: 23 Aug 2023 02:47
by green
I think, corrected version of my command would be with quotes just after the equal sign rather than before.

Code: Select all

SET/P="TEXT"<NUL|CLIP
As for the space origin, previously I thought that there is no difference between redirection with '>' and piping with '|', but now I reconsider that. Thanks for your explanation. I also offer my two cents to illustrate the difference.

Code: Select all

SET/P=TEXT<NUL>TEST&FIND /C " "<TEST
SET/P=TEXT<NUL|FIND /C " "

Re: avoid trailing space when piping to CLIP

Posted: 23 Aug 2023 03:10
by shodan
That's an awesome debug trick. I've been doing batch programming all summer and this is the first time I come across of it.
Is there a wiki or some exhaustive repertory of all these advanced programming methods ?