帮助编写批处理脚本来解析 CSV 文件并输出文本文件 [英] Help in writing a batch script to parse CSV file and output a text file

查看:36
本文介绍了帮助编写批处理脚本来解析 CSV 文件并输出文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力编写一个可以读取 CSV 文件的批处理脚本,如下所示

I am struggling to write a batch script which can read a CSV file such as below

Name:, City:, Country:
Mark, London, UK
Ben, Paris, France
Tom, Athens, Greece

CSV 文件中会有一个标题行.它应该输出到一个文本文件,如下所示:

There will be a heading row in the CSV file. It should output to a text file as below:

Name:Mark
City:London
Country:UK

Name:Ben
City:Paris
Country:France

Name:Tom
City:Athens
Country:Greece

上述输出中的字段分隔符 (:) 应在标题行本身中提供.所以我需要做的就是连接字段标题和它的值.

The field separator (:) in the above output is expected to be provided in the header row itself. So all that I need to do is concatenate the field heading and its value.

此 CSV 文件中的列数不是固定的,因此脚本不应限制为 3 个标记.请帮忙!

The number of columns in this CSV file is not fixed, so the script should not limit to 3 tokens. Kindly help!

推荐答案

@ECHO OFF
IF "%~1"=="" GOTO :EOF
SET "filename=%~1"
SET fcount=0
SET linenum=0
FOR /F "usebackq tokens=1-10 delims=," %%a IN ("%filename%") DO ^
CALL :process "%%a" "%%b" "%%c" "%%d" "%%e" "%%f" "%%g" "%%h" "%%i" "%%j"
GOTO :EOF

:trim
SET "tmp=%~1"
:trimlead
IF NOT "%tmp:~0,1%"==" " GOTO :EOF
SET "tmp=%tmp:~1%"
GOTO trimlead

:process
SET /A linenum+=1
IF "%linenum%"=="1" GOTO picknames

SET ind=0
:display
IF "%fcount%"=="%ind%" (ECHO.&GOTO :EOF)
SET /A ind+=1
CALL :trim %1
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !f%ind%!!tmp!
ENDLOCAL
SHIFT
GOTO display

:picknames
IF %1=="" GOTO :EOF
CALL :trim %1
SET /a fcount+=1
SET "f%fcount%=%tmp%"
SHIFT
GOTO picknames

这个批处理脚本:

  • 接受一个参数,要处理的文件名;

  • accepts one parameter, the name of the file to process;

不验证头标记末尾是否存在:,当显示值时,它们紧跟在相应的头标记之后;

does not verify the presence of : at the end of a header token, and when the values are displayed they are placed immediately after the corresponding header tokens;

修剪所有前导空格(但不是尾随空格);

trims all the leading spaces (but not the trailing ones);

将第一行视为标题行,这也定义了后续行中要处理的标记数;

considers the first row to be the header row, which also defines the number of tokens to process in subsequent rows;

最多支持10个token,粗斜体突出显示的两个区域负责(所以当你需要改变最大数量时,修改两个区域:如果你增加了数量,你必须扩大<代码>"%%a" "%%b" "%%c"... 列表,同样,如果减少数字,则缩小列表).

supports up to 10 tokens, and the two areas highlighted in bold italics are responsible for that (so when you need to change the maximum number, modify both areas: if you increase the number, you must expand the "%%a" "%%b" "%%c" … list, and, likewise, if you decrease the number, then shrink the list).

这篇关于帮助编写批处理脚本来解析 CSV 文件并输出文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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