【问题标题】:Batch script not outputting files with this code批处理脚本不使用此代码输出文件
【发布时间】:2019-01-29 03:41:53
【问题描述】:

此脚本应输出存储在第 1 行中的 10 个单词句子中的每个单词(当使用separateLine.bat (filename) 1 调用时,它不会显示错误,也不会输出或生成文件。

我已经尝试删除(echo %%a > 1.txt) 和下面的括号,但无济于事。我也尝试了不同的输出格式,但仍然无济于事。

@echo off
if not exist "%~1" echo file not found & exit /b 1
if "%~2"=="" echo line not defined & exit /b
if "%~2"=="1" set line=1 & goto start
set /a line=%~2-1
:start
For /f "tokens=1,2,3,4,5,6,7,8,9,10* usebackq skip=%line% delims= " %%A in ("%~1") do (                       
    if not "%%A"=="" (echo %%A > 1.txt)
    if not "%%B"=="" (echo %%B > 2.txt)
    if not "%%C"=="" (echo %%C > 3.txt)
    if not "%%D"=="" (echo %%D > 4.txt)
    if not "%%E"=="" (echo %%E > 5.txt)
    if not "%%F"=="" (echo %%F > 6.txt)
    if not "%%G"=="" (echo %%G > 7.txt)
    if not "%%H"=="" (echo %%H > 8.txt)
    if not "%%I"=="" (echo %%I > 9.txt)
    if not "%%J"=="" (echo %%J > 10.txt)
    GOTO endforloop
)
:endforloop

文件包含一、二、三...十个用空格隔开,它应该输出10个文件(最大字数限制为10个)每个文件包含行的第1-10个单词(我在第二个中指定了第1行参数,因为单词在第一行),但实际结果是......什么都没有。从字面上看,它就好像它成功完成了一样,但没有生成文件,而且没有错误代码。

【问题讨论】:

  • 括号内不能有:lablegoto。另外,这是完全没有必要的。
  • 正如我所说,我已经尝试删除括号。
  • 去掉goto是完全没有必要的。
  • 提供一些示例输入文本和您的预期输出,以便我们帮助您尝试。
  • @catcat goto 标签并不是完全没有必要的,OP 的意图是只打印给定行的内容然后退出循环,如果你删除 goto,它将重复剩余的循环线...

标签: file batch-file for-loop


【解决方案1】:

我认为这将是您正在寻找的。请注意,您不能在skip=%line% 中使用预定义变量,而需要使用more +%line%,不需要定义每个标记token=1,2,3,4... 等。只需使用tokens1-10 和最后一个,但并非最不需要使用delims= 作为空格是默认分隔符:

@echo off
if not exist "%~1" echo file not found & exit /b 1
if "%~2"=="" echo line not defined & exit /b
if "%~2"=="1" set line=1 & goto start
set /a line=%~2-1
:start
For /f "tokens=1-10" %%A in ('type "%~1" ^| more +%line%') do (              
    if "%%A" NEQ "" echo %%A
    if not "%%B"=="" echo %%B
    if not "%%C"=="" echo %%C
    if not "%%D"=="" echo %%D
    if not "%%E"=="" echo %%E
    if not "%%F"=="" echo %%F
    if not "%%G"=="" echo %%G
    if not "%%H"=="" echo %%H
    if not "%%I"=="" echo %%I
    if not "%%J"=="" echo %%J
    goto :EOF
)

但是您的 line 变量存在缺陷。

如果用户选择0,它将执行0 - = -1and then set the lines to skip-1if a user selects2it will set it to skip1`,这不是用户要求的,所以我建议你澄清你的意图是什么使用跳线,但也许完全摆脱它,例如:

@echo off
if not exist "%~1" echo file not found & exit /b 1
if "%~2"=="" echo line not defined & exit /b
set /a line=%~2
:start
For /f "tokens=1-10" %%A in ('type "%~1" ^| more +%line%') do (              
    if "%%A" NEQ "" echo %%A
    if not "%%B"=="" echo %%B
    if not "%%C"=="" echo %%C
    if not "%%D"=="" echo %%D
    if not "%%E"=="" echo %%E
    if not "%%F"=="" echo %%F
    if not "%%G"=="" echo %%G
    if not "%%H"=="" echo %%H
    if not "%%I"=="" echo %%I
    if not "%%J"=="" echo %%J
    goto :EOF
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    相关资源
    最近更新 更多