在批处理脚本中循环文件名 [英] Loop through file names in a Batch Script

查看:136
本文介绍了在批处理脚本中循环文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个批处理脚本文件夹中的所有文本文档。
这是我到目前为止所管理的:

  @ECHO off 
title Test
set dir1 = C:\Users\Family\Desktop\Example

:开始
cls
echo 1.测试循环
echo 2.退出
set / p choice = I choose(1,2):
如果%choice%== 1 goto test
如果%choice%== 2 exit

: test
cls
echo running loop test
FOR %% n in(%dir1%* .txt)DO echo%dir1%\ %% n
echo Done
pause

我想输出的是:

 运行循环测试
C:\Users\Family\Desktop\Example\doc 1.txt
C:\Users \ Family\Desktop\Example\doc 2.txt
Done

但我获得:

 运行循环测试
C:\Users\Family\ Desktop \Example \C:\Users\Family\Desktop\Example
C:\Users\Family\Desktop\Example \doc 1.txt
C: \Users\Family\Desktop\Example\doc 2.txt
Done


解决方案

主要问题似乎是(%dir1%* .txt)之间的空格



>

  @ECHO off 
title Test
setdir1 = C:\Users\Family\Desktop\\ \\Example

:开始
cls
echo 1.测试循环
echo 2.退出
set / p choice = I choose ):
if%choice%== 1 goto test
if%choice%== 2 exit

:test
cls
echo运行循环测试
FOR %% X in(%dir1%\ * .txt)DO echo %%〜dpnX
echo Done
pause

引号用于避免路径中的空格或其他特殊字符出现问题。



EDIT:

%%〜dpnX 用于扩展 %% X

d =驱动器(C :)

p = path(\Users\Family\Desktop\Example)

n = filename(test1) / p>

f =完整档案名称(C:\Users\Family\Desktop\Example\test1。 txt)。



可能的修饰符在此解释 FOR /?


I would like a batch script to all the text documents in a folder. This is what I have managed so far:

@ECHO off
title Test
set dir1=C:\Users\Family\Desktop\Example

:Start
cls
echo 1. test loop
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto test
if %choice%==2 exit

:test
cls
echo running loop test 
FOR %%n in (%dir1% *.txt) DO echo %dir1%\%%n
echo Done
pause

What I would like outputted is:

running loop test
C:\Users\Family\Desktop\Example\doc 1.txt
C:\Users\Family\Desktop\Example\doc 2.txt
Done

But I Get this:

running loop test
C:\Users\Family\Desktop\Example\C:\Users\Family\Desktop\Example
C:\Users\Family\Desktop\Example\doc 1.txt
C:\Users\Family\Desktop\Example\doc 2.txt
Done

解决方案

The main problem seems to be the space between (%dir1% *.txt)

It could be

@ECHO off
title Test
set "dir1=C:\Users\Family\Desktop\Example"

:Start
cls
echo 1. test loop
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto test
if %choice%==2 exit

:test
cls
echo running loop test 
FOR %%X in ("%dir1%\*.txt") DO echo %%~dpnX
echo Done
pause

The quotes are for avoiding problems with spaces or other special characters in the path.

EDIT:
The %%~dpnX is for expanding the filename of %%X to
d=drive(C:)
p=path(\Users\Family\Desktop\Example)
n=filename(test1) (without extension)

f=full filename(C:\Users\Family\Desktop\Example\test1.txt).

The possible modifiers are explained here FOR /?

这篇关于在批处理脚本中循环文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆