Windows Batch 脚本 -For loop 一览

0x01 如何读取csv 文件内容

  • 用 for /f

Salary.csv

name,country,city,salary
John,UK,London,5000
Mary,German,Berlin,5300
Peter,US,Boston,3000

read_salary.bat

@echo off

for /f "skip=1 delims=, tokens=1,2,3" %%i in (%cd%\salary.csv) do (
    echo input=%%i %%j %%k
)

Execution

C:\Users\inakamono\wk\coding\batch>dir
 Volume in drive C is OS
 Volume Serial Number is CE42-F672

 Directory of C:\Users\inakamono\wk\coding\batch

09/17/2020  09:41 PM    <DIR>          .
09/17/2020  09:41 PM    <DIR>          ..
09/17/2020  09:42 PM               115 read_salary.bat
09/17/2020  09:40 PM                92 salary.csv
               2 File(s)            207 bytes
               2 Dir(s)  46,528,008,192 bytes free

C:\Users\inakamono\wk\coding\batch>read_salary.bat
input=John UK London
input=Mary German Berlin
input=Peter US Boston
C:\Users\inakamono\wk\coding\batch>

0x02 如何读取文件夹内的文件

  • 用 for /r

loop_files.bat

@echo off

set test=%cd%

echo %test%
for /r %test% %%F IN (*) DO (
    echo %%F
)

Execution

C:\Users\inakamono\wk\coding\batch>dir
 Volume in drive C is OS
 Volume Serial Number is CE42-F672

 Directory of C:\Users\inakamono\wk\coding\batch

09/17/2020  09:52 PM    <DIR>          .
09/17/2020  09:52 PM    <DIR>          ..
09/17/2020  09:56 PM                89 loop_files.bat
09/17/2020  09:42 PM               115 read_salary.bat
09/17/2020  09:40 PM                92 salary.csv
               3 File(s)            296 bytes
               2 Dir(s)  46,535,454,720 bytes free

C:\Users\inakamono\wk\coding\batch>loop_files.bat
C:\Users\inakamono\wk\coding\batch
C:\Users\inakamono\wk\coding\batch\loop_files.bat
C:\Users\inakamono\wk\coding\batch\read_salary.bat
C:\Users\inakamono\wk\coding\batch\salary.csv

C:\Users\inakamono\wk\coding\batch>

FOR - Loop through a set of files in one folder.
FOR /R - Loop through files (recurse subfolders) .
FOR /D - Loop through several folders.
FOR /L - Loop through a range of numbers.
FOR /F - Loop through items in a text file.
FOR /F - Loop through the output of a command.

参考
For loop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值