首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在未更改格式的批处理文件的文本文件中添加新行

在未更改格式的批处理文件的文本文件中添加新行
EN

Stack Overflow用户
提问于 2011-09-13 16:00:41
回答 1查看 1K关注 0票数 1

这是我的脚本。

代码语言:javascript
复制
@ECHO OFF
SET origfile="C:\Documents and Settings\user\Desktop\test1\before.txt"
SET tempfile="C:\Documents and Settings\user\Desktop\test1\after.txt"
SET insertbefore=4
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C

<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /P L=
  IF %%i==%insertbefore% ECHO(
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
pause

这个脚本我另存为run1.bat。运行后,我对格式有问题。格式无序:尾随的制表符被删除。如何修复它?

原始文件:

代码语言:javascript
复制
header 1<--here got tab delimited format--><--here got tab delimited format-->
header 2<--here got tab delimited format--><--here got tab delimited format-->
header 3<--here got tab delimited format--><--here got tab delimited format-->
details 1
details 2

输出:

代码语言:javascript
复制
header 1<--tab delimited is missing--><--tab delimited is missing-->
header 2<--tab delimited is missing--><--tab delimited is missing-->
header 3<--tab delimited is missing--><--tab delimited is missing-->

details 1
details 2
details 3
EN

回答 1

Stack Overflow用户

发布于 2011-09-13 21:29:14

set /p阅读真的很强大,因为它不会改变任何字符。

但它会删除(额外的)尾随的CR/LF/TAB字符。

在这里How Set/p works和这里New technic: set /p can read multiple lines from a file解释了set/p的工作原理

为了解决您的问题并保留尾随选项卡,您需要delayed toggling technic

因此,您的代码将如下所示

代码语言:javascript
复制
@echo off
SET origfile="C:\Documents and Settings\user\Desktop\test1\before.txt"
SET tempfile="C:\Documents and Settings\user\Desktop\test1\after.txt"
SET insertbefore=4
set LineCnt=0
SETLOCAL DisableDelayedExpansion
(
  FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ %origfile%"`) do (
    set "var=%%a"
    set /a lineCnt+=1
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    IF !lineCnt!==%insertbefore% ECHO(
    echo(!var!
    ENDLOCAL
  )
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7398594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档