查看txt文件内部并从txt中查找拒绝权限然后打印下10行的批处理文件

时间:2015-10-19 13:46:08

标签: batch-file

我需要创建一个批处理脚本,它将查看txt文件并从中搜索“permission denied”字符串。

如果脚本会找到上面的字符串,那么它将打印下面10行,这些行在搜索字符串后面可用(“权限被拒绝”)。

下面是我正在尝试的代码,但它没有提供所需的结果:

for /F "delims=:" %%a in ('findstr /I /N /C:"permission denied" %temp%') do                 (
echo %%a
set /A after=%%a
set nextline=!after!+1
set "numbers=!after!:"
echo !numbers!
echo %nextline%
)
rem Search for the lines
for /F "tokens=1* delims=" %%a in ('findstr /N "^" %temp% ^| findstr /B "%numbers%"') do echo %%~nb

以上代码我们只生成行号。不是内容。

3 个答案:

答案 0 :(得分:1)

这应该有效:

@echo off
SETLOCAL EnableDelayedExpansion
SET /a printLines=0
FOR /F "tokens=*" %%l IN (<your log file>) DO (
    SET line=%%l
    SET line=!line:permission denied=!
    IF NOT %%l==!line! SET /a printLines=11
    IF !printLines! GTR 0 (
        ECHO %%l
        SET /a printLines=!printLines!-1
    )
)
PAUSE

答案 1 :(得分:1)

之后的10行

@echo off
setlocal enabledelayedexpansion
set temp=input.txt
for /F "tokens=1 delims=:" %%a in ('findstr /I /N /C:"permission denied" "%temp%"') do (
    set /a start=%%a + 1
    set /a end=%%a + 10
)
FOR /L %%I IN (%start%,1,%end%) DO SET LINES=!LINES! %%I:
FOR /F "TOKENS=* delims= " %%G in ("!lines!") DO SET lines=%%G 

echo %lines%

rem Search for the lines
for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%temp%" ^| findstr /B "%lines%"') do echo %%b
pause

之前的10行

@echo off
setlocal enabledelayedexpansion
set temp=input.txt
for /F "tokens=1 delims=:" %%a in ('findstr /I /N /C:"permission denied" "%temp%"') do (
    set /a start=%%a - 10
    set /a end=%%a -1
)
IF %start% lss 1 set start=1
FOR /L %%I IN (%start%,1,%end%) DO SET LINES=!LINES! %%I:
FOR /F "TOKENS=* delims= " %%G in ("!lines!") DO SET lines=%%G 

echo %lines%

rem Search for the lines
for /F "tokens=1* delims=:" %%a in ('findstr /N "^" "%temp%" ^| findstr /B "%lines%"') do echo %%b
pause

答案 2 :(得分:1)

我认为这是最快/最简单的方法:

@echo off
setlocal EnableDelayedExpansion

set "temp=input.txt"
for /F "delims=:" %%a in ('findstr /I /N /C:"permission denied" "%temp%"') do set "line=%%a"

set lines=0
for /F "delims=" %%a in ('more +%line% "%temp%"') do (
   echo %%a
   set /A lines+=1
   if !lines! equ 10 goto break
)
:break

要在匹配行之前显示10行,只需按do set "line=%%a"更改do set /A "line=%%a-11",然后在下面添加以下行:if %line% lss 0 set "line=0"