How to remove New line character from batch variable
Asked Answered
M

2

6

Good Day All! I have a batch script, and when I echo a variable like this

echo %variable1%

I get out put like this

TestLine1
TestLine2
TestLine3
TestLine4

My goal would be to modify this variable to remove all the newline characters so the output would look more like

TestLine1TestLine2TestLine3TestLine4

Is there a simple way to do this without creating files? Thank you for your assistance.

Millimicron answered 16/11, 2017 at 17:2 Comment(3)
It's not the easiest thing in the world to get newlines into an environment variable. Are you sure that your output is from echoing just one variable once, not from executing echo`s in a loop?Erie
Use this: set /p ".=%variable1%"<nulEleonoreleonora
@Eleonoreleonora can you explain what your code does, and demonstrate it in a working example?Osteology
T
0

First, get a newline into a variable:

setlocal EnableDelayedExpansion
(set LF=^
%=%
)

then, do variable string replacement:

call set oneline=%%variable1:!LF!=%%

et voila, newlines removed!

example:

@echo off
setlocal EnableDelayedExpansion
(set LF=^
%=%
)
set multiline=line1!LF!line2!LF!line3
echo !multiline!
call set oneline=%%multiline:!LF!=%%
echo %oneline%

output:

line1
line2
line3
line1line2line3
Trunk answered 24/6, 2024 at 20:23 Comment(0)
H
-2

You can use the command tr:

cleanedVariable1=$(echo $variable1 | tr -d '\n' )
echo $cleanedVariable1

The command tr removes or translates characters. The option -d removes the given characters. In this case, we are removing all new lines from our variable and assign it to a new variable.

Hyozo answered 14/2, 2020 at 18:26 Comment(2)
That's powershell, not batch, and that's a gnu tool, not a native windows tool. That's why the question was downvoted.Osteology
@Osteology that's not even powershell. var=$() is sh/bash/zsh syntax, in powershell you need $var = cmd. Besides, tr is a POSIX tool so it's not available at all unless you installed the necessary tools. And \n is definitely wrong because the escape character in powershell is backtick `` ` ``Featherston

© 2022 - 2025 — McMap. All rights reserved.