Windows Batch File - Need to remove line breaks from parameter

16,457

First, I can't believe that you have really linefeeds in your parameter %1, as it is possible, but a bit complex to achieve this.
To control this you could use

echo on
rem # %1 #

To handle CR and linefeed characters you have to use the delayed expansion, as percent expansion of such a content is not possible.
With percent expansion CR's are always removed, linefeeds removes the rest of the line or in a block context they append a new command line.

So it's not possible to handle content with linefeeds in a parameter like %1 ..%9.
You need it stored in a variable.

Assuming you have content with newlines in a variable, you could replace it with spaces.
The empty lines in this example are important for the result.

@echo off
set text=This contains a ^

newline
setlocal EnableDelayedExpansion
set ^"result=!text:^

= !"
echo Content of text is   "!text!"
echo ----
echo Content of result is "!result!"

--- Output ---

Content of text is   "This contains a
newline"
----
Content of result is "This contains a  newline"
Share:
16,457
Malk
Author by

Malk

Updated on June 05, 2022

Comments

  • Malk
    Malk almost 2 years

    I have a powershell script that will run a query and export the results to Excel. I want to hook this into SQL Studio Management Studio (2008)'s external tools. SSMS will not allow powershell scripts so I am using a batch file to get it started.

    In the external tools section you can specify some predefined arguments. The argument that I want is called "current text". This argument passes whatever is highlighted to the tool (batch file). My batch file then passes that argument on to a powershell script.

    The problem is that if the user has a query that spans multiple lines highlighted then the powershell script fails because of the linebreaks. It seems it would be relatively easy to strip them out, or better yet, replace them with a space?

    Here is my batch file:

    echo %~1
    call powershell ^& 'c:\temp\ExportSQL.ps1' -query "%~1"
    

    My question is how can I replace newlines and carriage returns from %1 with a space before passing it to the powershell script? TIA.