Windows echo перевод строки

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!

  1. Understanding New Lines in Batch Script

  2. Method 1: Using Echo with a Blank Line

  3. Method 2: Using Echo with a Carriage Return

  4. Method 3: Using a for Loop to Create Multiple New Lines

  5. Conclusion

  6. FAQ

New Line in Batch Script

Creating a new line in Batch Script can seem like a small task, but it plays a pivotal role in making your scripts more readable and organized. Whether you’re writing scripts for automation, file manipulation, or system administration, understanding how to manage line breaks effectively is crucial.

In this tutorial, we will explore various methods to create a new line in Batch Script, ensuring that you can enhance the clarity of your scripts. By the end of this guide, you’ll have a solid grasp of the techniques and commands necessary to implement new lines seamlessly. Let’s dive in!

Understanding New Lines in Batch Script

Before we get into the methods, it’s essential to understand what a new line is in the context of Batch Script. A new line is a command that tells the script to start a new line in the output. This can be particularly useful when you want to format your output for better readability. Unlike other programming languages, Batch Script requires specific commands to create new lines, as it doesn’t support multi-line strings directly.

Method 1: Using Echo with a Blank Line

One of the simplest ways to create a new line in Batch Script is by using the echo command with no arguments. This method is straightforward and effective for inserting blank lines in your output.

@echo off
echo This is the first line.
echo.
echo This is the second line.

Output:

This is the first line.

This is the second line.

In this example, the @echo off command suppresses the command prompt from displaying the commands themselves. The first echo outputs the first line of text. The second echo command, which is empty, generates a new line in the output. Finally, the last echo command prints the second line of text. This method is particularly useful for enhancing the readability of your script’s output.

Method 2: Using Echo with a Carriage Return

Another effective method to create a new line is by using the echo command combined with a carriage return character. This technique allows you to control the output format more precisely.

@echo off
echo This is the first line. 
echo [newline] This is the second line.

Output:

This is the first line. 
This is the second line.

In this snippet, the echo command is used to print the first line. The [newline] placeholder illustrates where the new line would occur. However, in Batch Script, you can’t directly insert a new line character like in other programming languages. Instead, you can use the method mentioned above to create a blank line. Although this method is more conceptual, it highlights the importance of formatting in your scripts.

Method 3: Using a for Loop to Create Multiple New Lines

If you need to create multiple new lines in your Batch Script, a for loop can be incredibly useful. This method allows you to specify how many new lines you want to insert and can be adapted for various situations.

@echo off
echo This is the first line.
for /L %%i in (1,1,3) do echo.
echo This is the fourth line.

Output:

This is the first line.

This is the fourth line.

In this example, the for /L command creates a loop that iterates three times, executing the echo. command during each iteration. This effectively inserts three blank lines in the output. After the loop, we print the fourth line of text. This method is particularly beneficial when you want to format your output with multiple line breaks, allowing for a more organized display.

Conclusion

Creating new lines in Batch Script is a fundamental skill that can greatly improve the readability and organization of your scripts. By utilizing the echo command and understanding how to manipulate output formatting, you can ensure that your scripts are not only functional but also user-friendly. Whether you’re a beginner or an experienced user, these methods will help you manage your Batch Script outputs more effectively. Don’t hesitate to experiment with these techniques to find what works best for your specific needs.

FAQ

  1. How do I create a new line in Batch Script?
    You can create a new line by using the echo. command, which outputs a blank line.

  2. Can I create multiple new lines in Batch Script?
    Yes, you can use a for loop to create multiple new lines by executing the echo. command multiple times.

  3. Is there a way to insert a new line without using echo?
    Batch Script primarily relies on the echo command for output, so using echo is the most straightforward method.

  4. What is the purpose of @echo off in a Batch Script?
    The @echo off command prevents the script from displaying the commands being executed, making the output cleaner.

  1. Are there any limitations to creating new lines in Batch Script?
    Yes, Batch Script does not support multi-line strings directly, so you need to use specific commands to manage line breaks.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Содержание

  • 1 Пробелы в значениях переменных
  • 2 Разрыв строки текста, перенос строки команд
  • 3 Экранирование служебных спецсимволов

Пробелы в значениях переменных

С переменной, в значении которой есть один или несколько пробелов, можно работать как и обычно..

Set PathBase=c:\Program Files\Firefox
Set StartProcess=%PathBase%\Firefox.exe

Но не всегда это работает и в тех случаях, когда по синтаксису пробел не должен находиться в этом месте, тогда используют обрамляющие кавычки

Set PathBase=c:\Program Files\Firefox
echo "%PathBase%\profiles.ini"

Но в некоторых случаях и тот и тот вариант может не подойти, тогда уж наверняка вас выручит иной вариант с кавычками, мой любимый

Set "PathBase=c:\Program Files\Firefox"
echo %PathBase%\profiles.ini

Разрыв строки текста, перенос строки команд

Если текст вашей команды слишком длинный, то это делает сценарий менее наглядным и удобочитаемым. Символ ^ должен быть последним в строке и означает, что следующая строка является продолжением текущей. Возможно разбиение команд более, чем на две строки. Заметим, при печати в консоли на выходе будет все же одна строка. Данный способ применяется только для более удобного восприятия и форматирования длинного кода листинга.

echo ^
Этот способ работает^
не только для текста^
но и для команд

Если нужно сделать перенос печатаемого текста в самой консоли, то просто используется новая команда с новой строки echo ваш текст.
Если нужна пустая строка на выходе, то используйте команду echo с точкой, то есть echo. в консоли выведет пустую строку.

Экранирование служебных спецсимволов

В командном языке Windows существует некоторый набор символов с высоким приоритетом, которые всегда трактуются как спецсимволы. К ним, в частности, относятся:

  • Операторы перенаправления ввода-вывода <, >, >>.
  • Оператор конвейера |.
  • Операторы объединения команд ||, & и &&.
  • Оператор разыменования переменной %…%.

В случае со знаком процента решение довольно хорошо известно и состоит в удвоении этого символа. Для других символов тут нам и придет на помощь уже известный знак домика — символ ^.

:: Это не сработает, вызовет ошибку - > was unexpected at this time.
echo <html>

:: А это сработает
echo ^<html^>

Этим же символом домика можно экранировать и любой другой символ, включая самого себя.

Продолжение следует..

How to echo new line break or blank line and write to file in DOS programming..

In this post, Learn how to add a new line to the text displayed with the echo command in a batch file.

For example, Want to print the text in multiple lines as given below

line1
line1

There are multiple ways to break lines in echo text.

You can use echo: to insert the new blank line in the command line output.

multiplelines.bat

@echo off
echo one
echo:
echo two

On running multiplelines.bat in the command line,
Output is shown as

one

two

Similarly, replace the above with a single syntax using the & operator.

@echo off & echo one & echo:& echo two

Other alternatives to echo: are below

echo(
echo+
echo,
echo;
echo+

How to echo a multi-line and write to a text file?

using the > symbol outputs to the filename

@echo off & echo one & echo:& echo two > multlines.txt

Like other scripting languages, we can also echo a new line in a batch file. If you are searching for a solution to how to echo a new line in a batch file, then this article for you. There are many ways to echo the new line but here I will only explain the sample to print a ‘new line’ in the batch script.

Different ways to echo new line in batch file:

1. Using echo function call:

We can echo a blank line on the screen using any type of echo.

echo,

echo;

echo(

echo/

echo+

echo=

echo.

echo\

echo:

Now let’s see an example of how to echo a new line in a batch file.

@echo off

echo Hi&echo\Aticleworld

pause

While running this batch file:

echo new line batch file

This means you could define &echo\ as a constant for a newline \n. You can use any one of the above-mentioned echo types.

2. Using ‘EnableDelayedExpansion’:

@echo off

setlocal EnableDelayedExpansion
(set \n=^
%=Don't remove this line=%
)

echo Hi!\n!Aticleworld

pause

Output:

print new line in batch script

Note: In place of “Don’t remove this line”, you can write anything.

3. Using new line variable hack:

@echo off
REM Creating a Newline variable (the two blank lines are required!)
set NLC=^


set NL=^^^%NLC%%NLC%^%NLC%%NLC%
REM Example Usage:
echo Hi%NL%Aticleworld.

pause

Output:

echo new line in batch script

Different ways to echo a blank line in batch file:

At the beginning of the article, I have already explained that using the echo command you can echo a blank line. You can use any one of the echo types which have mentioned above like echo. , echo, or echo; …etc.

Let’s see some example batch script to see how we can echo blank lines in the batch file.

Using the echo,

@echo off

@echo HI

@echo,

@echo Aticleworld

pause

Output:

HI

Aticleworld

Using echo.

@echo off

@echo HI

@echo.

@echo Aticleworld

pause

Output:

HI

Aticleworld

Note: Don’t include a space before the period. Otherwise, the period appears instead of a blank line. Let’s see an example script to understand this point.

@echo off

@echo HI

@echo .

@echo Aticleworld

pause

Output:

HI
.
Aticleworld

Recommended Articles for you:

  • Batch file introduction.
  • Best Gifts for the programmer and techies.
  • Best mouse for a programmer.
  • File handling in C, In a few hours.
  • List of Batch script commands.
  • How to create variables in the batch script.
  • Batch script to copy files from one folder to another folder.
  • How to use if-else statements in the batch script.
  • for loop in the batch file.
  • How to pass parameters in a batch file.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 10 clear clipboard
  • Linux основные отличия от windows
  • Ограничить доступ к сайтам на компьютере windows 10
  • Control panel windows 2000
  • Как завести будильник на компьютере windows 10