在批处理脚本中为变量分配换行符 [英] Assigning newline character to a variable in a batch script

查看:34
本文介绍了在批处理脚本中为变量分配换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我写的批处理脚本

The following is the batch script i have written

@echo off
setlocal enabledelayedexpansion
set finalcontent=
For /F "tokens=1-2* delims=  " %%I in (abc.txt) do (
IF %%J EQU MAJORVER (
set currentline=%%I %%J %1
set finalcontent=!finalcontent!!currentline!
) ELSE IF %%J EQU MINORVER (
set currentline=%%I %%J %2
set finalcontent=!finalcontent!!currentline!
) ELSE IF %%J EQU BUILDNUM (
set currentline=%%I %%J %3
set finalcontent=!finalcontent!!currentline!
) ELSE (
set currentline=%%I %%J %%K%NL%
set finalcontent=!finalcontent!!currentline!
)
)
echo %finalcontent%>>xyz.txt

我想要在变量 currentline 每次出现的末尾附加一个换行符.任何人都可以指导我吗?

I want a newline character appended at the end of every occurence of the variable currentline. Can anyone guide me on this?

推荐答案

您可以创建一个真正的换行符并将其分配给一个变量.

You can create a real newline character and assign it to a variable.

setlocal EnableDelayedExpansion
set LF=^


rem TWO empty lines are required
echo This text!LF!uses two lines

换行符最适用于延迟扩展,您也可以将它与百分比扩展一起使用,但它有点复杂.

The newline best works with delayed expansion, you can also use it with the percent expansion, but then it's a bit more complex.

set LF=^


rem TWO empty lines are required
echo This text^%LF%%LF%uses two lines
echo This also^

uses two lines

它是如何工作的?
插入符号是一个转义字符,它转义下一个字符并删除它本身.
但是如果下一个字符是换行符,则换行符也会被删除,并且只有下一个字符被有效地转义(即使这也是一个换行符).

How it works?
The caret is an escape character, it escapes the next character and itself is removed.
But if the next character is a linefeed the linefeed is also removed and only the next character is effectivly escaped (even if this is also an linefeed).

因此,需要两个空行,LF1被忽略,LF2被转义,LF3是完成行"所必需的.

Therefore, two empty lines are required, LF1 is ignored LF2 is escaped and LF3 is neccessary to finish the "line".

set myLinefeed=^<LF1>
<LF2>
<LF3>

提示:
使用完全不同的换行变量定义格式通常会更好,以避免无意中删除所需的空行.

Hints:
It's often better to use a quite different format of the newline variable definition, to avoid an inadvertently deletion of the required empty lines.

(SET LF=^
%=this line is empty=%
)

我经常删除其中一个空行,然后我一直在寻找为什么我的程序不再工作了.

I have removed to often one of the empty lines and then I searched forever why my program didn't work anymore.

偏执版本还会检查换行符变量是否有空格或其他垃圾.

And the paranoid version checks also the newline variable for whitespaces or other garbage.

if "!LF!" NEQ "!LF:~0,1!" echo Error "Linefeed definition is defect, probably multiple invisble whitespaces at the line end in the definition of LF"

FOR /F "delims=" %%n in ("!LF!") do (
  echo Error "Linefeed definition is defect, probably invisble whitespaces at the line end in the definition of LF"
)

这篇关于在批处理脚本中为变量分配换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆