Windows Batch script * (star) read as text?

我的梦境 提交于 2019-12-02 20:04:38

问题


I'm writing a batch script to convert a fixed-width text file to .csv format. Here's what I've written so far:

@echo off
setlocal enabledelayedexpansion


    for /F "tokens=*" %%A in (HRV*.txt) do (
    set var=%%A
    set mer=!var:~6,11!
    set cr=!var:~18,19!

    set dt=!var:~42,30!
    set aa=!var:~72,30!
    set ab=!var:~102,30!
    set ac=!var:~132,15!

    set ad=!var:~147,30!
    set ae=!var:~177,30!

    set af=!var:~283,36!

    set ag=!var:~318,3!
    set ah=!var:~329,7!
    set ai=!var:~337,17!
    set aj=!var:~442,2!
    set ak=!var:~460,15!
    set al=!var:~475,2!
    set am=!var:~482,15!

    set y=!mer!.!cr!,"!dt!","!aa!","!ab!","!ac!","!ad!","!ae!",="!af!","!ag!",="ah","ai","aj",="ak","al",="am"
    echo !y!>> converted.csv
    )

pause

The problem is that when I run it, the program fails to complete, and outputs "The system cannot find the file HRV*.txt". I then changed for loop to

for /F "tokens=*" %%A in (*.txt) do ( ...

But the error just changed to "The system cannot find the file *.txt"

It seems that the star * is being read as text? does this have something to do with "tokens+*"? How can I make it so that the script will run on any file that starts with HRV?


回答1:


for /f expects a single file name and is not capable of using wildcards. Use another plain for around:

for %%X in (HRV*.txt) do (
  for /F "tokens=*" %%A in (%%X) do (
    ... etc. etc.
  )
)

by the way: your way of redirecting is very slow. The destination file is opened, one line is written and the file is closed again. Opening and closing a file is very time consuming. You can avoid it by opening and closing it just one time. Instead of:

for /l %%a in (1,1,10000) do (
  echo something>>file.txt
)

which needs about 27 seconds, do:

(
  for /l %%a in (1,1,10000) do (
    echo something
  )
)>file.txt

which needs about 170 ms. (Ymmv - times depends on your computer system)



来源:https://stackoverflow.com/questions/39453594/windows-batch-script-star-read-as-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!