1

嗨,伙计,我必须为 Windows shell 编写一个脚本 .bat。我有这个文件:

line
line
#line
line
#line

我想逐行读取文件,如果该行以“#”开头,我什么也不做,我会做一些详细说明。怎么能做到这一点?我发布伪代码

while (s=readline()!=null)
  {

  if(s.charat(0)!='#')
     do some elaboration
   }
4

3 回答 3

1

这是解决此问题的最快方法:

for /F "eol=# delims=" %%a in (file.txt) do (
   echo Line that not start with #: %%a
)
于 2013-04-16T17:53:39.140 回答
1

根据您的伪代码,这是您想要的吗?

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%i in (file.txt) do (
    set line=%%i
    if !line:~0,1! equ # (
        ::Your code here:
    )
)

请注意,您需要替换file.txt为要迭代的文件。

于 2013-04-16T06:28:57.303 回答
1
@ECHO OFF
SETLOCAL
:: first way - findstr
FOR /f "delims=" %%i IN (yourfile.txt) DO (
 ECHO %%i|FINDSTR /b "#" >NUL
 IF ERRORLEVEL 1 (ECHO non-#  : %%i) ELSE (ECHO #START : %%i)
)
ECHO ====== first way ===========
ENDLOCAL
SETLOCAL enabledelayedexpansion
:: second way - substring with delayedexpansion
FOR /f "delims=" %%i IN (yourfile.txt) DO (
 SET line=%%i
 if "!line:~0,1!"=="#" (ECHO #START : %%i) ELSE (ECHO non-#  : %%i)
)
ECHO ====== second way ===========
ENDLOCAL
SETLOCAL
:: third way -without delayedexpansion substringing and flagging in subroutine
FOR /f "delims=" %%i IN (yourfile.txt) DO (
 SET line=%%i
 CALL :test
 IF DEFINED line (ECHO non-#  : %%i) ELSE (ECHO #START : %%i)
)
ECHO ====== third way ===========
ENDLOCAL

GOTO :eof

:test
IF "%line:~0,1%"=="#" SET "line="
GOTO :eof

这里有三种方式 - 取决于进一步的细节。请注意,第三种方式使用IF DEFINEDIF ERRORLEVEL适用于变量的 RUN-TIME 值的特性,而不是解析时间值

于 2013-04-16T07:11:49.773 回答