嗨,我必须使用Windows shell脚本.bat。 我有这个文件:
line
line
#line
line
#line
我想逐行读取文件,如果行以“#”开头,我不做任何其他事情我做一些详细说明。怎么办呢?我发布了伪代码
while (s=readline()!=null)
{
if(s.charat(0)!='#')
do some elaboration
}
答案 0 :(得分: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
替换为要迭代的文件。
答案 1 :(得分: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 DEFINED
或IF ERRORLEVEL
对变量的RUN-TIME值起作用的特性,而不是分析时间值
答案 2 :(得分:1)
这是解决此问题的最快方法:
for /F "eol=# delims=" %%a in (file.txt) do (
echo Line that not start with #: %%a
)