Windows command line new line

I’m trying to execute a command on cmd.exe, with a line break or new line as part of the command, like below:

command -option:text  
whatever

But every new line executes the command, instead of continuing the command on the next line.

So how can I input a new line character, or create a multi-line command in cmd.exe?

HopelessN00b's user avatar

HopelessN00b

1,8823 gold badges21 silver badges29 bronze badges

asked Jun 8, 2010 at 9:38

rudimenter's user avatar

2

Use the ^ character as an escape:

command -option:text^ 
whatever

I’m assuming you’re using cmd.exe from Windows XP or later. This is not actual DOS. If you are using actual DOS (MS-DOS, Win3.1, Win95, Win98, WinME), then I don’t believe there is an escape character for newlines. You would need to run a custom shell. cmd.exe will prompt you for More? each time you press enter with a ^ at the end of the line, just press enter again to actually escape/embed a newline.

Wasif's user avatar

Wasif

8,0642 gold badges19 silver badges32 bronze badges

answered Jun 8, 2010 at 9:49

Darth Android's user avatar

Darth AndroidDarth Android

37.9k5 gold badges94 silver badges112 bronze badges

8

Use Alt codes with the numpad

C:\>ver

Microsoft Windows [Version 6.3.9600]

C:\>echo Line1◙Line2 >con
Line1
Line2

C:\>

That line feed character can be entered as an Alt code on the CLI using the numpad: with NumLock on, hold down ALT and type 10 on the numpad before releasing ALT. If you need the CR as well, type them both with Alt+13 and then Alt+10 : ♪◙

Note: this will not work in a batch file.

Sample use case:

You are trying to read the %PATH% or %CLASSPATH% environment variables to get a quick overview of what’s there and in what order — but the wall of text that path returns is unreadable. Then this is something you can quickly type in:

echo %path:;=◙% >con

Edit:

Added the >con workaround that Brent Rittenhouse discovered for newer versions of cmd.exe, where the original method had stopped working.

Community's user avatar

answered Oct 8, 2016 at 1:28

Amit Naidu's user avatar

Amit NaiduAmit Naidu

5497 silver badges10 bronze badges

8

I don’t know if this will work for you but by putting &echo (the following space is important). in between each statement that you want on a new line. I only tried this with a simple bat file of

echo %1

Then saved that as testNewLines.bat

So then the cmd line

testNewLines first line&echo Second Line&echo Third line

Resulted in the following being echoed back

first line
second line
Third line

answered Jun 8, 2010 at 13:10

Haydar's user avatar

HaydarHaydar

1212 bronze badges

^‘s output are saveable.

set br= ^
<</br (newline)>>
<</br>>

Example:

@echo off
setlocal enableExtensions enableDelayedExpansion
rem cd /D "%~dp0"


rem //# need 2 [/br], can't be saved to a var. by using %..%;
set br= ^



set "t=t1!br!t2!br!t3"

for /f "tokens=* delims=" %%q in ("!t!") do (
    echo %%q
)


:scIn
rem endlocal
pause
rem exit /b

; output:

t1
t2
t3
Press any key to continue . . .

Wasif's user avatar

Wasif

8,0642 gold badges19 silver badges32 bronze badges

answered Apr 2, 2019 at 10:10

ilias's user avatar

iliasilias

1314 bronze badges

Expanding on @Amit’s answer (https://superuser.com/a/1132659/955256) I found a way to do it in any font WITHOUT using the legacy console.

All you need to do is simply echo out the line with ALT-10 characters and then redirect it to con and it will work!

For example, given:

(echo New-line detected rigghhhtt ◙^<— HERE!) > CON

edit: Fun fact, it seems that you can put the redirection at the beginning like so:

> CON echo New-line detected rigghhhtt ◙^<— HERE!

Weird, eh?

You will get an output of:


New-line detected rigghhhtt  
<-- HERE!

(The surrounding parenthesis are optional.)

Here is a more robust example of what you can do with this AND carriage returns which now work, and completely independently!:

Best of all, this works if you redirect to a file as well!
(simply change > CON to > desired_output_file.txt

Enjoy!

Wasif's user avatar

Wasif

8,0642 gold badges19 silver badges32 bronze badges

answered Oct 18, 2018 at 18:10

Brent Rittenhouse's user avatar

I believe you can’t do that from the Windows cmd.exe shell. (It is not DOS.)


You do not need a full «custom shell» for that. You will only need to write something like this (example in Python):

import subprocess
subprocess.call(["C:\\bin\\sometool.exe", "test\nwith\nnewlines"])

Or Ruby:

Kernel::exec "C:\\bin\\sometool.exe", "test\nwith\nnewlines"

See, it’s not that hard.

answered Jun 8, 2010 at 12:46

u1686_grawity's user avatar

u1686_grawityu1686_grawity

430k64 gold badges899 silver badges973 bronze badges

Install Powershell Core

Inside your batch file:

MyBatchFile.bat

@echo off
echo Hello
pwsh.exe -Command [System.Console]::WriteLine()
echo world

Wasif's user avatar

Wasif

8,0642 gold badges19 silver badges32 bronze badges

answered May 24, 2020 at 23:10

Joma's user avatar

JomaJoma

1313 bronze badges

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

In a Windows Command Prompt (CMD) and PowerShell when you execute the echo command to print some text or redirect it to a file, you can break it into multiple lines.

In Linux you can do this by using the \n.

This short note shows how to break lines and insert new lines using the echo command from the Command Prompt (CMD) and Windows PowerShell.

Cool Tip: Windows grep command equivalent in CMD and PowerShell! Read more →

Windows Command Prompt (CMD)

To insert a line break in the Windows Command Prompt, you can use multiple echo commands as follows:

C:\> (echo Line & echo Newline) > file.txt
C:\> type file.txt
Line
Newline

To print a new line in the Windows Command Prompt, use the echo., for example:

C:\> (echo Line & echo. & echo Newline) > file.txt
C:\> type file.txt
Line

Newline

Windows PowerShell

To insert a line break in the Windows PowerShell, you can use the `n character:

PS C:\> echo "Line`nNewline" > file.txt
PS C:\> type file.txt
Line
Newline

The same `n character can be used to insert a new line in the Windows PowerShell:

PS C:\> echo "Line`n`nNewline" > file.txt
PS C:\> type file.txt
Line

Newline

Was it useful? Share this post with the world!

Solution 1

Use the ^ character as an escape:

command -option:text^ 
whatever

I’m assuming you’re using cmd.exe from Windows XP or later. This is not actual DOS. If you are using actual DOS (MS-DOS, Win3.1, Win95, Win98, WinME), then I don’t believe there is an escape character for newlines. You would need to run a custom shell. cmd.exe will prompt you for More? each time you press enter with a ^ at the end of the line, just press enter again to actually escape/embed a newline.

Solution 2

Use Alt codes with the numpad

C:\>ver

Microsoft Windows [Version 6.3.9600]

C:\>echo Line1◙Line2 >con
Line1
Line2

C:\>

That line feed character can be entered as an Alt code on the CLI using the numpad: with NumLock on, hold down ALT and type 10 on the numpad before releasing ALT. If you need the CR as well, type them both with Alt+13 and then Alt+10 : ♪◙

Note: this will not work in a batch file.

Sample use case:

You are trying to read the %PATH% or %CLASSPATH% environment variables to get a quick overview of what’s there and in what order — but the wall of text that path returns is unreadable. Then this is something you can quickly type in:

echo %path:;=◙% >con

Edit:

Added the >con workaround that Brent Rittenhouse discovered for newer versions of cmd.exe, where the original method had stopped working.

Solution 3

I don’t know if this will work for you but by putting &echo (the following space is important). in between each statement that you want on a new line. I only tried this with a simple bat file of

echo %1

Then saved that as testNewLines.bat

So then the cmd line

testNewLines first line&echo Second Line&echo Third line

Resulted in the following being echoed back

first line
second line
Third line

Solution 4

^‘s output are saveable.

set br= ^
<</br (newline)>>
<</br>>

Example:

@echo off
setlocal enableExtensions enableDelayedExpansion
rem cd /D "%~dp0"


rem //# need 2 [/br], can't be saved to a var. by using %..%;
set br= ^



set "t=t1!br!t2!br!t3"

for /f "tokens=* delims=" %%q in ("!t!") do (
    echo %%q
)


:scIn
rem endlocal
pause
rem exit /b

; output:

t1
t2
t3
Press any key to continue . . .

Solution 5

Expanding on @Amit’s answer (https://superuser.com/a/1132659/955256) I found a way to do it in any font WITHOUT using the legacy console.

All you need to do is simply echo out the line with ALT-10 characters and then redirect it to con and it will work!

For example, given:

(echo New-line detected rigghhhtt ◙^<— HERE!) > CON

edit: Fun fact, it seems that you can put the redirection at the beginning like so:

> CON echo New-line detected rigghhhtt ◙^<— HERE!

Weird, eh?

You will get an output of:


New-line detected rigghhhtt  
<-- HERE!

(The surrounding parenthesis are optional.)

Here is a more robust example of what you can do with this AND carriage returns which now work, and completely independently!:

Best of all, this works if you redirect to a file as well!
(simply change > CON to > desired_output_file.txt

Enjoy!

Related videos on Youtube

How can I insert a new line in a cmd.exe command? (7 Solutions!!)

05 : 09

How can I insert a new line in a cmd.exe command? (7 Solutions!!)

Windows Command Line - Net Share | Net Use | Net View | Net User

19 : 39

Windows Command Line — Net Share | Net Use | Net View | Net User

Command Prompt Basics: How to use CMD

18 : 41

Command Prompt Basics: How to use CMD

How to Use New Command Prompt - CMD Line Console in Windows 10 Tutorial

04 : 17

How to Use New Command Prompt — CMD Line Console in Windows 10 Tutorial

Windows Command Line Tutorial - 1 - Introduction to the Command Prompt

07 : 31

Windows Command Line Tutorial — 1 — Introduction to the Command Prompt

Comments

  • I’m trying to execute a command on cmd.exe, with a line break or new line as part of the command, like below:

    command -option:text  
    whatever
    

    But every new line executes the command, instead of continuing the command on the next line.

    So how can I input a new line character, or create a multi-line command in cmd.exe?

  • Too cool, I did not know that.

  • This what you suggests is the allows me to enter more text on a newline. It does not preserve the newline. What i want is that between «text» and «whatever» is an newline. Something like this: «text\nwhatever»

  • I believe you have to use two newlines to do that, my bad for not realizing this in my original post (now edited)

  • @T.J. Crowder I know, I didn’t either until I looked it up for another question on here a few days ago.

  • It should be noted that if you have spaces in the text, you will need to wrap them in quotes. Further, make sure that you include the end quote, otherwise the caret will be ignored as an escape character and treated like text. Finally, you will need to put quotes around the text on each line containing spaces (do so even if it doesn’t contain spaces to be safe), and put a caret after the closing quote for each line that continues.

  • I ended up here by trying to find a way to put newlines in the comments of a SHUTDOWN.EXE command. I ended up using something like this: shutdown -s -t 900 -c "foo bar"^ > More? "baz"^ > More? "test that." It worked.

  • Unfortunately there seems to be no way to include a newline character inside a quoted string.

  • This doesn’t seem to work for me. I end up with e2 99 aa e2 97 99 passed in. Some sort of unicode code point? I do see the characters go in on the command line though. Any suggestions?

  • @Brad I can confirm it doesn’t seem to be working any more in the new cmd.exe in Windows 10 and even my old Windows 7 box won’t behave this way anymore.

  • Weird! I wonder if I can dig up an old cmd.exe from something….

  • @Brad, I just tried and few things and realized that you can get that old behavior if you switch to Raster Fonts in console properties, instead of Lucida and True Type fonts and check the Use legacy console checkbox. But it looks really bad on a high res monitor.

  • Oh wow! Weird. Someone just commented that in powershell, I can use backtick-r-backtick-n, which works.

  • The craziest thing about this is that if you have a) use legacy console and b) raster fonts like specified it will work, and then if you switch the font to Lucida Console (or whatever it’s called) it will switch and you’ll see the text still with the new line in it, but if you try it now it won’t work. Even if you copy the line you JUST did and re-paste it (I thought maybe it was a differnet code page or something) it STILL won’t work. Example: i.imgur.com/kKX2jiy.png

  • Actually, I think I’ve found a solution that works for this completely in ANY font! If you simply echo out the line with alt-10 characters and then redirect it to CON it will work! For example: (echo New-line detected rigghhhtt ◙^<--- HERE!) > CON The surrounding parenthesis are optional. Here is a more robust example of what you can do with this (AND carriage returns which now work, and completely independently!): i.imgur.com/qqN37PH.png

  • @BrentRittenhouse Wow, nicely done! I tested it with my path echo and it works beautifully now. I have missed this for a long time, so thank you ! echo %path:;=◙% >con. @Brad, heads up.

  • Yeah, DOS COMMAND.COM was soooooo horrible !!

  • Powershell comes by default on Windows 7+

Recents

Table of Contents

  • 1 How do I add a new line in CMD?
  • 2 How do I go to a second line in CMD?
  • 3 What is the command for next line?
  • 4 How do you go down a line in CMD?
  • 5 How do you write multiple lines in R console?
  • 6 How can I insert a new line in cmd.exe command?
  • 7 How do you add a new line after a match?
  • 8 What are the commands in the command line?
  • 9 How to insert a line after the match in Linux?
  • 10 How to add line numbers in every line using shell command?

To start a new line in batch, all you have to do is add “echo[“, like so: echo Hi! echo[ echo Hello!

How do I go to a second line in CMD?

In the Windows Command Prompt the ^ is used to escape the next character on the command line. (Like \ is used in strings.) Characters that need to be used in the command line as they are should have a ^ prefixed to them, hence that’s why it works for the newline.

How do you go to next line in command prompt without pressing enter?

If you are searching for a way to move the cursor down a line without pressing the Enter key but still break the current line at that point, consider using a line break (Ctrl+Shift+L).

What is the command for next line?

Adding Newline Characters in a String. Operating systems have special characters denoting the start of a new line. For example, in Linux a new line is denoted by “\n”, also called a Line Feed. In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF.

How do you go down a line in CMD?

To enter multiple lines before running any of them, use Shift+Enter or Shift+Return after typing a line. This is useful, for example, when entering a set of statements containing keywords, such as if end. The cursor moves down to the next line, which does not show a prompt, where you can type the next line.

How do you write multiple lines in PowerShell?

To execute multiline command in one line in PowerShell, use semicolon (;) after each command. You can also use pipe operator (|) to chain commands and execute it based on conditions.

How do you write multiple lines in R console?

There are three ways to execute multiple lines from within the editor:

  1. Select the lines and press the Ctrl+Enter key (or use the Run toolbar button); or.
  2. After executing a selection of code, use the Re-Run Previous Region command (or its associated toolbar button) to run the same selection again.

How can I insert a new line in cmd.exe command?

That line feed character can be entered as an Alt code on the CLI using the numpad: with NumLock on, hold down ALT and type 10 on the numpad before releasing ALT. If you need the CR as well, type them both with Alt+13 and then Alt+10 : ♪◙. Note: this will not work in a batch file.

Is there a way to increase the number of lines on the command line?

Windows’ command line tool only remembers 300 lines by default – this can be a nuisance especially if you are working with long list outputs. However you can easily increase the number of lines that are shown.

How do you add a new line after a match?

The following “sed” command shows how a new line can be added anywhere in the file based on the matching pattern. The pattern used in the “sed” command will search any line starting with “s01”, and add the new string after it.

What are the commands in the command line?

Many Windows console commands are based on batch files. This are usually text files (with the ending .bat or .cmd) that are run by the command line as batch processing. These files are generally created to perform routine work and start other programs.

How to add a new line between text?

How to add a new line between text. How to add some blank lines between your command execution (batch echo blank line). To echo a new line in a batch file, you can create a new line character as ^^^%NLC%%NLC%^%NLC%%NLC% and echo it or use echo; or echo (or echo/ or echo+ or echo= in a single line to insert a blank line in between your code.

How to insert a line after the match in Linux?

Sed is a command in Linux that can perform various tasks such as insert, update, and delete a particular text or line based on the match. Inserting a text in a string or a file in different ways is done using the “sed” command.

How to add line numbers in every line using shell command?

You may want to tune w idth option according to the total number of lines in the file (if you want numbers to be aligned nicely). In Linux/Unix, there are almost always multiple ways to do common tasks.

How to add line numbers in every line?

Just for completeness, here are some other ways you can do it besides the obvious: From an old command to format text to send to a line printer. The ‘-t’ will omit header and footer information that are not relevant to a terminal. Here’s a cute sed method that prints the line number on every other line.

After a sleepless night and after reading all answers herein, after reading a lot of SS64 > CMD and after a lot of try & error I found:

The (almost) Ultimate Solution

TL;DR

… for early adopters.

Important!
Use a text editor for C&P that supports Unicode, e.g. Notepad++!

Set Newline Environment Variable …

… in the Current CMD Session

Important!
Do not edit anything between ‘=‘ and ‘^‘! (There’s a character in between though you don’t see it. Neither here nor in edit mode. C&P works here.)
:: Sets newline variables in the current CMD session
set n=​^&echo(
set nl=​^&echo(

… for the Current User

Important!
Do not edit anything between (the second) ‘‘ and ‘^‘! (There’s a character in between though you don’t see it. Neither here nor in edit mode. C&P works here.)
:: Sets newline variables for the current user [HKEY_CURRENT_USEREnvironment]
setx n ​^&echo(
setx nl ​^&echo(

… for the Local Machine

Important!
Do not edit anything between (the second) ‘‘ and ‘^‘! (There’s a character in between though you don’t see it. Neither here nor in edit mode. C&P works here.)
:: Sets newline variables for the local machine [HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment]
setx n ​^&echo( /m 
setx nl ​^&echo( /m 

Why just almost?

It does not work with double-quotes that are not paired (opened and closed) in the same printed line, except if the only unpaired double-quote is the last character of the text, e.g.:

  • works: ""echo %n%...after "newline". Before "newline"...%n%...after "newline" (paired in each printed line)

  • works: echo %n%...after newline. Before newline...%n%...after newline" (the only unpaired double-quote is the last character)

  • doesn’t work: echo "%n%...after newline. Before newline...%n%...after newline" (double-quotes are not paired in the same printed line)

    Workaround for completely double-quoted texts (inspired by Windows batch: echo without new line):

    set BEGIN_QUOTE=echo ^| set /p !="""
    ...
    %BEGIN_QUOTE%
    echo %n%...after newline. Before newline...%n%...after newline"
    

It works with completely single-quoted texts like:

echo '%n%...after newline. Before newline...%n%...after newline'

Added value: Escape Character

Note
There’s a character after the ‘=‘ but you don’t see it here but in edit mode. C&P works here.
:: Escape character - useful for color codes when 'echo'ing
:: See https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#text-formatting
set ESC=

For the colors see also https://imgur.com/a/EuNXEar and https://gist.github.com/gerib/f2562474e7ca0d3cda600366ee4b8a45.

2nd added value: Getting Unicode characters easily

A great page for getting 87,461 Unicode characters (AToW) by keyword(s): https://www.amp-what.com/.

The Reasons

  • The version in Ken’s answer works apparently (I didn’t try it), but is somehow…well…you see:

    set NLM=^
    
    
    set NL=^^^%NLM%%NLM%^%NLM%%NLM%
    
  • The version derived from user2605194’s and user287293’s answer (without anything between ‘=‘ and ‘^‘):

    set nl=^&echo(
    set n=^&echo(
    

    works partly but fails with the variable at the beginning of the line to be echoed:

    > echo %n%Hello%n%World!
    echo   & echo(Hello & echo(World!
    echo is ON.
    Hello
    World
    

    due to the blank argument to the first echo.

  • All others are more or less invoking three echos explicitely.

  • I like short one-liners.

The Story Behind

To prevent set n=^&echo: suggested in answers herein echoing blank (and such printing its status) I first remembered the Alt+255 user from the times when Novell was a widely used network and code pages like 437 and 850 were used. But 0d255/0xFF is ›Ÿ‹ (Latin Small Letter Y with diaeresis) in Unicode nowadays.

Then I remembered that there are more spaces in Unicode than the ordinary 0d32/0x20 but all of them are considered whitespaces and lead to the same behaviour as ›␣‹.

But there are even more: the zero width spaces and joiners which are not considered as whitespaces. The problem with them is, that you cannot C&P them since with their zero width there’s nothing to select. So, I copied one that is close to one of them, the hair space (U+200A) which is right before the zero width space (U+200B) into Notepad++, opened its Hex-Editor plugin, found its bit representation E2 80 8A and changed it to E2 80 8B. Success! I had a non-whitespace character that’s not visible in my n environment variable.

More often, we need to add new line between lines for string output to make output neat and easy to read. Using Windows PowerShell new line can be easily added to text output or variables.

In this blog post, I will explain adding new line in string output or variable, and how to use PowerShell new line ` (backtick) character to add new line.

PowerShell Tip: If you need a PowerShell carriage return, use `r. Use `n to add PowerShell new line. For a carriage return and new line, use `r`n

PowerShell - add newline to string (carriage return)

add PowerShell new line to string (carriage return)

There are different ways to add newline to string or variable in PowerShell using carriage return `r or line continuation character ` at the end of code.

Backtick (`) character is the PowerShell line continuation character. It ensures the PowerShell script continues to a new line.

To use the line continuation character in PowerShell, type space at the end of the code, use backtick ` and press enters to continue to a new line.

Add PowerShell Newline – Using `r carriage return

Use the special character `r for carriage return in PowerShell. The below example shows how to use `r PowerShell carriage return

PS C:>"Shell `r`nGeek"

In the above example, it add a newline with PowerShell carriage return (`r) and gives output as

Shell
Geek

Do you know: How to use the cat command in windows!

PowerShell new line in string output

Use `n to add newline in string output in PowerShell. The below example shows how to use PowerShell new line `n in string output.

PS C:>"Welcome to Shell Geek `nIts all about PowerShell"

In the above example, using `n in the string, add newline in string output in PowerShell. The output of the above command as below

Welcome to Shell Geek
Its all about PowerShell

Cool Tip: Tail – Get the last lines of a file in PowerShell!

Using PowerShell newline in Command

More often, we have longer PowerShell script commands and we want to beautify them using multiline statements instead of one single-line command.

To add newline in the PowerShell script command, use the` (backtick) character at the end of each line to break the command into multiple lines.

In the below example, we want to get free disk space on a local computer name is a single-line command which makes it very difficult to read and manage.

We can easily break it using ` (PowerShell backtick character) for line continuation in a given command

Get-CimInstance -ComputerName localhost win32_logicaldisk | where caption -eq "C:" | foreach-object {write " $($_.caption) $('{0:N2}' -f ($_.Size/1gb)) GB total, $('{0:N2}' -f ($_.FreeSpace/1gb)) GB free "}

After using ` (PowerShell backtick character) for a line break in the command, it can be easily read

Get-CimInstance -ComputerName localhost win32_logicaldisk `
| where caption -eq "C:" `
| foreach-object {write " $($_.caption) $('{0:N2}' `
-f ($_.Size/1gb)) GB total, $('{0:N2}' `
-f ($_.FreeSpace/1gb)) GB free "}

As seen in the above example, using the ` line continuation character in PowerShell to continue code in a new line.

Cool Tip: Use Test Connection to ping a list of computers in PowerShell!

Using PowerShell carriage return `r or `n, you can add PowerShell newline in variable or newline in string output for the variable as below

PS C:>$strOutput = "Welcome you to Shell Geek `r`nIts all about PowerShell" 
PS C:>$strOutput
Welcome you to Shell Geek
Its all about PowerShell

In the above PowerShell script to add newline to a variable, we define a variable with string text and added `n to create newline for variable output.

When we print the strOutut variable on the terminal, it gives output with a line break in between the string output.

Cool Tip: Replace text in a string using PowerShell!

Add PowerShell new line with Write-Host

Using `n to add a newline in string output using the PowerShell Write-Host command. The below command prints new line string on the console

PS C:>Write-Host "Welcome you to Shell Geek `nIts all about PowerShell"
Welcome you to Shell Geek
Its all about PowerShell

In the above script, using PowerShell Write-Host newline is added with `n and prints the string on the console with new line in the text.

Cool Tip: Do you know how to download a zip file in PowerShell?

PowerShell Add New Line to Array

If you want to add new line to array using PowerShell, you have to use the pipe operator to pipe the array variable to Out-String.

Let’s consider an example of an Employee array having employee names stored in an array variable as below

$EmployeeArrayList = 'Tom Smith','Adam Strauss','Tim Smith','Gary willy'

$EmployeeArrayList variable contains lists of employees separated by a comma. To print the array line by line or add new line to the array using the below PowerShell script

$EmployeeArrayList = 'Tom Smith','Adam Strauss','Tim Smith','Gary willy'

$empArray = $EmployeeArrayList  | Out-String

Write-Host $empArray

In the first command, we store the list of employees in variable $EmployeeArrayList

The second command uses an array variable and pipes its output to Out-String and stores the result in a temporary $empArray variable.

The third command uses the PowerShell Write-host cmdlet to print the array on the console.

The output of the above script in PowerShell to add new line in Array as below

PowerShell Print array multiple lines

PowerShell Print array multiple lines

Cool Tip: PowerShell String Concatenation with Examples!

Conclusion

I hope you found the above article about different ways to add PowerShell newline to variable or string output in PowerShell helpful.

Using PowerShell carriage return and PowerShell newline ` (backtick character) at the end of each line to break the command in multiple lines.

You can also create a PowerShell new line break while defining a string as below

 PS C:> "Shell
>>Geek"
Shell
Geek

Read more here about how to create a multiline string in PowerShell!

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.

Newline inserted between the words «Hello» and «world»

Newline (frequently called line ending, end of line (EOL), next line (NEL) or line break) is a control character or sequence of control characters in character encoding specifications such as ASCII, EBCDIC, Unicode, etc. This character, or a sequence of characters, is used to signify the end of a line of text and the start of a new one.[1]

History[edit]

In the mid-1800s, long before the advent of teleprinters and teletype machines, Morse code operators or telegraphists invented and used Morse code prosigns to encode white space text formatting in formal written text messages. In particular the Morse prosign BT (mnemonic break text) represented by the concatenation of literal textual Morse codes «B» and «T» characters sent without the normal inter-character spacing is used in Morse code to encode and indicate a new line or new section in a formal text message.

Later, in the age of modern teleprinters, standardized character set control codes were developed to aid in white space text formatting. ASCII was developed simultaneously by the International Organization for Standardization (ISO) and the American Standards Association (ASA), the latter being the predecessor organization to American National Standards Institute (ANSI). During the period of 1963 to 1968, the ISO draft standards supported the use of either CR+LF or LF alone as a newline, while the ASA drafts supported only CR+LF.

The sequence CR+LF was commonly used on many early computer systems that had adopted Teletype machines—typically a Teletype Model 33 ASR—as a console device, because this sequence was required to position those printers at the start of a new line. The separation of newline into two functions concealed the fact that the print head could not return from the far right to the beginning of the next line in time to print the next character. Any character printed after a CR would often print as a smudge in the middle of the page while the print head was still moving the carriage back to the first position. «The solution was to make the newline two characters: CR to move the carriage to column one, and LF to move the paper up.»[2] In fact, it was often necessary to send extra characters—extraneous CRs or NULs—which are ignored but give the print head time to move to the left margin. Many early video displays also required multiple character times to scroll the display.

On such systems, applications had to talk directly to the Teletype machine and follow its conventions since the concept of device drivers hiding such hardware details from the application was not yet well developed. Therefore, text was routinely composed to satisfy the needs of Teletype machines. Most minicomputer systems from DEC used this convention. CP/M also used it in order to print on the same terminals that minicomputers used. From there MS-DOS (1981) adopted CP/M’s CR+LF in order to be compatible, and this convention was inherited by Microsoft’s later Windows operating system.

The Multics operating system began development in 1964 and used LF alone as its newline. Multics used a device driver to translate this character to whatever sequence a printer needed (including extra padding characters), and the single byte was more convenient for programming. What seems like a more obvious choice—CR—was not used, as CR provided the useful function of overprinting one line with another to create boldface, underscore and strikethrough effects. Perhaps more importantly, the use of LF alone as a line terminator had already been incorporated into drafts of the eventual ISO/IEC 646 standard. Unix followed the Multics practice, and later Unix-like systems followed Unix. This created conflicts between Windows and Unix-like operating systems, whereby files composed on one operating system could not be properly formatted or interpreted by another operating system (for example a UNIX shell script written in a Windows text editor like Notepad[3][4]).

Representation[edit]

The concepts of carriage return (CR) and line feed (LF) are closely associated and can be considered either separately or together. In the physical media of typewriters and printers, two axes of motion, «down» and «across», are needed to create a new line on the page. Although the design of a machine (typewriter or printer) must consider them separately, the abstract logic of software can combine them together as one event. This is why a newline in character encoding can be defined as CR and LF combined into one (commonly called CR+LF or CRLF).

Some character sets provide a separate newline character code. EBCDIC, for example, provides an NL character code in addition to the CR and LF codes. Unicode, in addition to providing the ASCII CR and LF control codes, also provides a «next line» (NEL) control code, as well as control codes for «line separator» and «paragraph separator» markers.

  • EBCDIC systems—mainly IBM mainframe systems, including z/OS (OS/390) and IBM i (OS/400)—use NL (New Line, 0x15)[8] as the character combining the functions of line feed and carriage return. The equivalent Unicode character (0x85) is called NEL (Next Line). EBCDIC also has control characters called CR and LF, but the numerical value of LF (0x25) differs from the one used by ASCII (0x0A). Additionally, some EBCDIC variants also use NL but assign a different numeric code to the character. However, those operating systems use a record-based file system, which stores text files as one record per line. In most file formats, no line terminators are actually stored.
  • Operating systems for the CDC 6000 series defined a newline as two or more zero-valued six-bit characters at the end of a 60-bit word. Some configurations also defined a zero-valued character as a colon character, with the result that multiple colons could be interpreted as a newline depending on position.
  • RSX-11 and OpenVMS also use a record-based file system, which stores text files as one record per line. In most file formats, no line terminators are actually stored, but the Record Management Services facility can transparently add a terminator to each line when it is retrieved by an application. The records themselves can contain the same line terminator characters, which can either be considered a feature or a nuisance depending on the application. RMS not only stores records, but also stores metadata about the record separators in different bits for the file to complicate matters even more (since files can have fixed length records, records that are prefixed by a count or records that are terminated by a specific character). The bits are not generic, so while they can specify that CRLF or LF or even CR is the line terminator, they can not substitute some other code.
  • Fixed line length was used by some early mainframe operating systems. In such a system, an implicit end-of-line was assumed every 72 or 80 characters, for example. No newline character was stored. If a file was imported from the outside world, lines shorter than the line length had to be padded with spaces, while lines longer than the line length had to be truncated. This mimicked the use of punched cards, on which each line was stored on a separate card, usually with 80 columns on each card, often with sequence numbers in columns 73–80. Many of these systems added a carriage control character to the start of the next record; this could indicate whether the next record was a continuation of the line started by the previous record, or a new line, or should overprint the previous line (similar to a CR). Often this was a normal printing character such as # that thus could not be used as the first character in a line. Some early line printers interpreted these characters directly in the records sent to them.

Unicode[edit]

«Paragraph separator» redirects here. For the symbol also known as a «paragraph sign», see Pilcrow.

The Unicode standard defines a number of characters that conforming applications should recognize as line terminators:[9]

 LF:    Line Feed, U+000A
 VT:    Vertical Tab, U+000B
 FF:    Form Feed, U+000C
 CR:    Carriage Return, U+000D
 CR+LF: CR (U+000D) followed by LF (U+000A)
 NEL:   Next Line, U+0085
 LS:    Line Separator, U+2028
 PS:    Paragraph Separator, U+2029

This may seem overly complicated compared to an approach such as converting all line terminators to a single character, for example LF. However, Unicode was designed to preserve all information when converting a text file from any existing encoding to Unicode and back. Therefore, Unicode should contain characters included in existing encodings.

For example: NL is part of EBCDIC, which uses code 0x15; it is normally mapped to Unicode NEL, 0x85, which is a control character in the C1 control set.[10] As such, it is defined by ECMA 48,[11] and recognized by encodings compliant with ISO/IEC 2022 (which is equivalent to ECMA 35).[12] C1 control set is also compatible with ISO-8859-1.[citation needed] The approach taken in the Unicode standard allows round-trip transformation to be information-preserving while still enabling applications to recognize all possible types of line terminators.

Recognizing and using the newline codes greater than 0x7F (NEL, LS and PS) is not often done. They are multiple bytes in UTF-8, and the code for NEL has been used as the ellipsis () character in Windows-1252. For instance:

  • ECMAScript accepts LS and PS as line-breaks,[13] but considers U+0085 (NEL) whitespace instead of a line-break.[14]
  • Windows 10 does not treat any of NEL, LS, or PS as line-breaks in its default text editor, Notepad.
  • gedit, the default text editor of the GNOME desktop environment, treats LS and PS as newlines but does not for NEL.
  • JSON[15] allows LS and PS characters within strings, while ECMAScript prior to ES2019[16][17] treated them as newlines, and therefore illegal syntax.[18]
  • YAML[19] no longer recognizes them as special as of version 1.2, in order to be compatible with JSON.

Note well that the Unicode special characters U+2424 (SYMBOL FOR NEWLINE, ), U+23CE (RETURN SYMBOL, ), U+240D (SYMBOL FOR CARRIAGE RETURN, ) and U+240A (SYMBOL FOR LINE FEED, ) are glyphs intended for presenting a user-visible character to the reader of the document, and are thus not recognized themselves as a newline.

In programming languages[edit]

To facilitate the creation of portable programs, programming languages provide some abstractions to deal with the different types of newline sequences used in different environments.

The C programming language provides the escape sequences ‘n’ (newline) and ‘r’ (carriage return). However, these are not required to be equivalent to the ASCII LF and CR control characters. The C standard only guarantees two things:

  1. Each of these escape sequences maps to a unique implementation-defined number that can be stored in a single char value.
  2. When writing to a file, device node, or socket/fifo in text mode, ‘n’ is transparently translated to the native newline sequence used by the system, which may be longer than one character. When reading in text mode, the native newline sequence is translated back to ‘n’. In binary mode, no translation is performed, and the internal representation produced by ‘n’ is output directly.

On Unix platforms, where C originated, the native newline sequence is ASCII LF (0x0A), so ‘n’ was simply defined to be that value. With the internal and external representation being identical, the translation performed in text mode is a no-op, and Unix has no notion of text mode or binary mode. This has caused many programmers who developed their software on Unix systems simply to ignore the distinction completely, resulting in code that is not portable to different platforms.

The C library function fgets() is best avoided in binary mode because any file not written with the Unix newline convention will be misread. Also, in text mode, any file not written with the system’s native newline sequence (such as a file created on a Unix system, then copied to a Windows system) will be misread as well.

Another common problem is the use of ‘n’ when communicating using an Internet protocol that mandates the use of ASCII CR+LF for ending lines. Writing ‘n’ to a text mode stream works correctly on Windows systems, but produces only LF on Unix, and something completely different on more exotic systems. Using «rn» in binary mode is slightly better.

Many languages, such as C++, Perl,[20] and Haskell provide the same interpretation of ‘n’ as C. C++ has an alternative I/O model where the manipulator std::endl can be used to output a newline (and flushes the stream buffer).

Java, PHP,[21] and Python[22] provide the ‘rn’ sequence (for ASCII CR+LF). In contrast to C, these are guaranteed to represent the values U+000D and U+000A, respectively.

The Java I/O libraries do not transparently translate these into platform-dependent newline sequences on input or output. Instead, they provide functions for writing a full line that automatically add the native newline sequence, and functions for reading lines that accept any of CR, LF, or CR+LF as a line terminator (see BufferedReader.readLine()). The System.lineSeparator() method can be used to retrieve the underlying line separator.

Example:

   String eol = System.lineSeparator();
   String lineColor = "Color: Red" + eol;

Python permits «Universal Newline Support» when opening a file for reading, when importing modules, and when executing a file.[23]

Some languages have created special variables, constants, and subroutines to facilitate newlines during program execution. In some languages such as PHP and Perl, double quotes are required to perform escape substitution for all escape sequences, including ‘n’ and ‘r’. In PHP, to avoid portability problems, newline sequences should be issued using the PHP_EOL constant.[24]

Example in C#:

   string eol = Environment.NewLine;
   string lineColor = "Color: Red" + eol;
   
   string eol2 = "n";
   string lineColor2 = "Color: Blue" + eol2;

Issues with different newline formats[edit]

The different newline conventions cause text files that have been transferred between systems of different types to be displayed incorrectly.

Text in files created with programs which are common on Unix-like or classic Mac OS, appear as a single long line on most programs common to MS-DOS and Microsoft Windows because these do not display a single line feed or a single carriage return as a line break.

Conversely, when viewing a file originating from a Windows computer on a Unix-like system, the extra CR may be displayed as a second line break, as ^M, or as <cr> at the end of each line.

Furthermore, programs other than text editors may not accept a file, e.g. some configuration file, encoded using the foreign newline convention, as a valid file.

The problem can be hard to spot because some programs handle the foreign newlines properly while others do not. For example, a compiler may fail with obscure syntax errors even though the source file looks correct when displayed on the console or in an editor. Modern text editors generally recognize all flavours of CR+LF newlines and allow users to convert between the different standards. Web browsers are usually also capable of displaying text files and websites which use different types of newlines.

Even if a program supports different newline conventions, these features are often not sufficiently labeled, described, or documented. Typically a menu or combo-box enumerating different newline conventions will be displayed to users without an indication if the selection will re-interpret, temporarily convert, or permanently convert the newlines. Some programs will implicitly convert on open, copy, paste, or save—often inconsistently.

Most textual Internet protocols (including HTTP, SMTP, FTP, IRC, and many others) mandate the use of ASCII CR+LF (‘rn’, 0x0D 0x0A) on the protocol level, but recommend that tolerant applications recognize lone LF (‘n’, 0x0A) as well. Despite the dictated standard, many applications erroneously use the C newline escape sequence ‘n’ (LF) instead of the correct combination of carriage return escape and newline escape sequences ‘rn’ (CR+LF) (see section Newline in programming languages above). This accidental use of the wrong escape sequences leads to problems when trying to communicate with systems adhering to the stricter interpretation of the standards instead of the suggested tolerant interpretation. One such intolerant system is the qmail mail transfer agent that actively refuses to accept messages from systems that send bare LF instead of the required CR+LF.[25]

The standard Internet Message Format[26] for email states: «CR and LF MUST only occur together as CRLF; they MUST NOT appear independently in the body».

The File Transfer Protocol can automatically convert newlines in files being transferred between systems with different newline representations when the transfer is done in «ASCII mode». However, transferring binary files in this mode usually has disastrous results: any occurrence of the newline byte sequence—which does not have line terminator semantics in this context, but is just part of a normal sequence of bytes—will be translated to whatever newline representation the other system uses, effectively corrupting the file. FTP clients often employ some heuristics (for example, inspection of filename extensions) to automatically select either binary or ASCII mode, but in the end it is up to users to make sure their files are transferred in the correct mode. If there is any doubt as to the correct mode, binary mode should be used, as then no files will be altered by FTP, though they may display incorrectly.[27]

Conversion between newline formats[edit]

Text editors are often used for converting a text file between different newline formats; most modern editors can read and write files using at least the different ASCII CR/LF conventions.

For example, the editor Vim can make a file compatible with the Windows Notepad text editor. Within vim

Editors can be unsuitable for converting larger files or bulk conversion of many files. For larger files (on Windows NT/2000/XP) the following command is often used:

D:>TYPE unix_file | FIND /V "" > dos_file

Special purpose programs to convert files between different newline conventions include unix2dos and dos2unix, mac2unix and unix2mac, mac2dos and dos2mac, and flip.[28]
The tr command is available on virtually every Unix-like system and can be used to perform arbitrary replacement operations on single characters. A DOS/Windows text file can be converted to Unix format by simply removing all ASCII CR characters with

$ tr -d 'r' < inputfile > outputfile

or, if the text has only CR newlines, by converting all CR newlines to LF with

$ tr 'r' 'n' < inputfile > outputfile

The same tasks are sometimes performed with awk, sed, or in Perl if the platform has a Perl interpreter:

$ awk '{sub("$","rn"); printf("%s",$0);}' inputfile > outputfile  # UNIX to DOS  (adding CRs on Linux and BSD based OS that haven't GNU extensions)
$ awk '{gsub("r",""); print;}' inputfile > outputfile              # DOS to UNIX  (removing CRs on Linux and BSD based OS that haven't GNU extensions)
$ sed -e 's/$/r/' inputfile > outputfile              # UNIX to DOS  (adding CRs on Linux based OS that use GNU extensions)
$ sed -e 's/r$//' inputfile > outputfile              # DOS  to UNIX (removing CRs on Linux based OS that use GNU extensions)
$ perl -pe 's/r?n|r/rn/g' inputfile > outputfile  # Convert to DOS
$ perl -pe 's/r?n|r/n/g'   inputfile > outputfile  # Convert to UNIX
$ perl -pe 's/r?n|r/r/g'   inputfile > outputfile  # Convert to old Mac

The file command can identify the type of line endings:

 $ file myfile.txt
 myfile.txt: ASCII English text, with CRLF line terminators

The Unix egrep (extended grep) command can be used to print filenames of Unix or DOS files (assuming Unix and DOS-style files only, no classic Mac OS-style files):

$ egrep -L 'rn' myfile.txt # show UNIX style file (LF terminated)
$ egrep -l 'rn' myfile.txt # show DOS style file (CRLF terminated)

Other tools permit the user to visualise the EOL characters:

$ od -a myfile.txt
$ cat -e myfile.txt
$ cat -v myfile.txt
$ hexdump -c myfile.txt

Interpretation[edit]

Two ways to view newlines, both of which are self-consistent, are that newlines either separate lines or that they terminate lines. If a newline is considered a separator, there will be no newline after the last line of a file. Some programs have problems processing the last line of a file if it is not terminated by a newline. On the other hand, programs that expect newline to be used as a separator will interpret a final newline as starting a new (empty) line. Conversely, if a newline is considered a terminator, all text lines including the last are expected to be terminated by a newline. If the final character sequence in a text file is not a newline, the final line of the file may be considered to be an improper or incomplete text line, or the file may be considered to be improperly truncated.

In text intended primarily to be read by humans using software which implements the word wrap feature, a newline character typically only needs to be stored if a line break is required independent of whether the next word would fit on the same line, such as between paragraphs and in vertical lists. Therefore, in the logic of word processing and most text editors, newline is used as a paragraph break and is known as a «hard return», in contrast to «soft returns» which are dynamically created to implement word wrapping and are changeable with each display instance. In many applications a separate control character called «manual line break» exists for forcing line breaks inside a single paragraph. The glyph for the control character for a hard return is usually a pilcrow (¶), and for the manual line break is usually a carriage return arrow (↵).

Reverse and partial line feeds[edit]

RI, (U+008D REVERSE LINE FEED,[29] ISO/IEC 6429 8D, decimal 141) is used to move the printing position back one line (by reverse feeding the paper, or by moving a display cursor up one line) so that other characters may be printed over existing text. This may be done to make them bolder, or to add underlines, strike-throughs or other characters such as diacritics.

Similarly, PLD (U+008B PARTIAL LINE FORWARD, decimal 139) and PLU (U+008C PARTIAL LINE BACKWARD, decimal 140) can be used to advance or reverse the text printing position by some fraction of the vertical line spacing (typically, half). These can be used in combination for subscripts (by advancing and then reversing) and superscripts (by reversing and then advancing), and may also be useful for printing diacritics.

See also[edit]

  • ASA carriage control characters
  • C0 and C1 control codes
  • End-of-file
  • Line starve
  • Page break
  • Carriage return
  • Enter key

References[edit]

  1. ^ «What is a Newline?». www.computerhope.com. Retrieved 10 May 2021.
  2. ^ Qualline, Steve (2001). Vi Improved — Vim (PDF). Sams Publishing. p. 120. ISBN 9780735710016. Archived from the original (PDF) on 8 April 2022. Retrieved 4 January 2023.
  3. ^ Duckett, Chris. «Windows Notepad finally understands everyone else’s end of line characters». ZDNet. Archived from the original on 13 May 2018. Retrieved 4 January 2023. [A]fter decades of frustration, and having to download a real text editor to change a single line in a config file from a Linux box, Microsoft has updated Notepad to be able to handle end of line characters used in Unix, Linux, and macOS environments.
  4. ^ Lopez, Michel (8 May 2018). «Introducing extended line endings support in Notepad». Windows Command Line. Archived from the original on 6 April 2019. Retrieved 4 January 2023. As with any change to a long-established tool, there’s a chance that this new behavior may not work for your scenarios, or you may prefer to disable this new behavior and return to Notepad’s original behavior. To do this, you can change […registry keys…] to tweak how Notepad handles pasting of text, and which EOL character to use when Enter/Return is hit
  5. ^ «ASCII Chart».
  6. ^ Bray, Andrew C.; Dickens, Adrian C.; Holmes, Mark A. (1983). The Advanced User Guide for the BBC Microcomputer (PDF). pp. 103, 104. ISBN 978-0946827008. Retrieved 30 January 2019.
  7. ^ «RISC OS 3 Programmers’ Reference Manual». Retrieved 18 July 2018.
  8. ^ IBM System/360 Reference Data Card, Publication GX20-1703, IBM Data Processing Division, White Plains, NY
  9. ^ «UAX #14: Unicode Line Breaking Algorithm». www.unicode.org.
  10. ^ «C1 Control Character Set of ISO 6429» (PDF). ITSCJ. IPSJ. 1 October 1983. Retrieved 3 March 2022.
  11. ^ Control Functions for Coded Character Sets (PDF) (Report). ECMA International. June 1991.
  12. ^ Character Code Structure and Extension Techniques (PDF) (Report) (6th ed.). ECMA International. December 1994.
  13. ^ «ECMAScript 2019 Language Specification». ECMA International. June 2019. 11.3 Line Terminators.
  14. ^ «ECMAScript 2019 Language Specification». ECMA International. June 2019. 11.2 White Space.
  15. ^ Bray, Tim (March 2014). «Strings». The JavaScript Object Notation (JSON) Data Interchange Format. sec. 7. doi:10.17487/RFC7159. RFC 7159.
  16. ^ «Subsume JSON (a.k.a. JSON ⊂ ECMAScript)». GitHub. 22 May 2018.
  17. ^ «ECMAScript 2019 Language Specification». ECMA International. June 2019. 11.8.4 String Literals.
  18. ^ «ECMAScript 2018 Language Specification». ECMA International. June 2018. 11.8.4 String Literals.
  19. ^ «YAML Ain’t Markup Language (YAML) Version 1.2». yaml.org. 5.4. Line Break Characters.
  20. ^ «binmode — perldoc.perl.org». perldoc.perl.org.
  21. ^ «PHP: Strings — Manual». www.php.net.
  22. ^ «Lexical analysis – Python v3.0.1 documentation». docs.python.org.
  23. ^ «What’s new in Python 2.3».
  24. ^ «PHP: Predefined Constants — Manual». www.php.net.
  25. ^ Bernstein, D.J. «Bare LFs in SMTP».
  26. ^ Resnick, Pete (April 2001). Internet Message Format. doi:10.17487/RFC2822. RFC 2822.
  27. ^ «File Transfer». When in doubt, transfer in binary mode.
  28. ^ «ASCII text conversion between UNIX, Macintosh, MS-DOS». Archived from the original on 9 February 2009.
  29. ^ «C1 Controls and Latin-1 Supplement» (PDF). unicode.org. Retrieved 13 February 2016.

External links[edit]

  • The Unicode reference, see paragraph 5.8 in Chapter 5 of the Unicode 4.0 standard (PDF)
  • «The [NEL] Newline Character».
  • The End of Line Puzzle
  • Line counter based on Newline Character
  • Understanding Newlines at the Wayback Machine (archived 20 August 2006)
  • «The End-of-Line Story»

  • Windows command line date command
  • Windows command line execute command
  • Windows cannot find make sure you typed the name correctly and then try again перевод
  • Windows cannot find google chrome
  • Windows cannot find bin javaw