如何从MS DOS目录列表中排除特定的文件名?

时间:2013-03-30 02:45:36

标签: batch-file dos

我正在创建一个MS DOS批处理脚本,需要列出当前目录中的每个.bat文件,但不显示autoexec.bat或其他不应由用户运行的实用程序或系统.bat文件。

我目前有DIR "*.bat" /B /P

这会正确列出所有.bat文件,但会显示autoexec.bat。我该如何从列表中排除它?同样有点重要的是,如何切断文件扩展名并显示超过7个字符的DOS限制文件?

约束:我无法使用WinME以上的DOS版本。那是我正在使用的版本。

感谢您的帮助。

修改 互联网上有很多关于这样做的信息,但它都在Windows命令处理器中,不是 MS DOS。请理解DOS和命令提示符不是一回事。

4 个答案:

答案 0 :(得分:7)

@echo off
setlocal EnableDelayedExpansion
rem Add more names separated with slashes here:
set exclude=/autoexec/
for %%a in (*.bat) do (
   if "!exclude:/%%~Na/=!" equ "%exclude%" (
      echo %%~Na
   )
)

编辑添加了一些解释

批处理文件处理速度很慢,因此您应该使用允许批处理文件运行得更快的技术。例如:

  • 尝试使用最小行/命令来获得特定结果。尽量避免使用findfindstrfc等外部命令(* .exe文件),特别是如果它们处理少量数据;改为使用if命令。
  • 使用for %%a in (*.bat)...代替for /F %%a in ('dir /B *.bat')...。第二种方法需要执行cmd.exe并在for命令处理其行之前将其输出存储在文件中。
  • 避免使用管道并改用重定向。管道需要执行两个cmd.exe副本才能在管道的每一侧处理命令。
  • 检查变量是否包含给定字符串的简单方法是尝试从变量中删除字符串:如果结果不同,则字符串存在于变量中:if "!variable:%string%=!" neq "%variable%" echo The string is in the variable
  • 以前的方法也可用于检查变量是否包含值列表中的任何一个:set list=one two threeif "!list:%variable%=!" neq "%list%" echo The variable have one value from the list。如果列表的值可能包含空格,则它们必须用另一个分隔符分隔。

编辑新版本已添加为新评论的回答

一次暂停一个页面的最简单方法是以这种方式使用more过滤器:

theBatchFile | more

但是,程序必须重新排序输出才能在列中显示。下面的新版本实现了这两个目标,因此不需要more过滤器;您只需要为每页设置所需的列数和行数。

@echo off
setlocal EnableDelayedExpansion
rem Add more names separated with slashes here:
set exclude=/autoexec/
rem Set the first two next variables as desired:
set /A columns=5, rows=41,   wide=(80-columns)/columns, col=0, row=0
rem Create filling spaces to align columns
set spaces=
for /L %%a in (1,1,%wide%) do set spaces= !spaces!
set line=
for %%a in (*.bat) do (
   if "!exclude:/%%~Na/=!" equ "%exclude%" (
      rem If this column is less than the limit...
      set /A col+=1
      if !col! lss %columns% (
         rem ... add it to current line
         set name=%%~Na%spaces%
         set "line=!line!!name:~0,%wide%! "
      ) else (
         rem ... show current line and reset it
         set name=%%~Na
         echo !line!!name:~0,%wide%!
         set line=
         set /a col=0, row+=1
         rem If this row is equal to the limit...
         if !row! equ %rows% (
            rem ...do a pause and reset row
            pause
            set row=0
         )
      )
   )
)
rem Show last line, if any
if defined line echo %line%

安东尼奥

答案 1 :(得分:2)

attrib +h autoexec.bat

应隐藏autoexec.bat,因此不应出现在列表中

答案 2 :(得分:1)

DIR "*.bat" /B /P | find /v "autoexec" | for %i in (*.bat) do @echo %~ni

答案 3 :(得分:0)

使用for分别处理每个文件名:

setlocal enabledelayedexpansion
for /f %%i in ('dir "*.bat" /b') do (
  set system=0
  if "%%i"=="autoexec.bat" set system=1
  if "%%i"=="somesystem.bat" set system=1
  if !system!==0 echo %%i
)

另一种没有变量的方法:

for /f %%i in ('dir "*.bat" /b') do call :test %%i
goto continue
  :test
  if "%1"=="autoexec.bat" goto :eof
  if "%1"=="somesystem.bat" goto :eof
  echo %1
  goto :eof
:continue

对于两者,您可以添加要从列表中排除的新文件名。