我以前从未做过任何批处理脚本,所以我需要帮助来构建其中一个。我们有一个文件说"GetHistory.bat",它接受一个参数ID。脚本的输出如下所示:
Activity Name Status Date
----------------------------------------
Act1 Created 1-Jan-2013
Act2 Submitted 2-Jan-2013
Act3 Approved 2-Jan-2013
现在的问题是我需要将 txt 中的输出导出为 CSV,而无需将标头和参数 ID 添加到每行,如下所示:
1001,Act1,Created,1-Jan-2013
1001,Act2,Submitted,2-Jan-2013
1001,Act3,Approved,2-Jan-2013
任何帮助开始脚本将不胜感激。谢谢。。。!
假设
GetHistory.bat
的输出已被重定向到一个名为 history.txt
的文件中,我们可以将其输入到新的批处理文件中,ParamCSV.bat
,如下所示,结果如下:
C:stackoverflow>ParamCSV.bat 1001 < history.txt
1001,Act1,Created,1-Jan-2013
1001,Act2,Submitted,2-Jan-2013
1001,Act3,Approved,2-Jan-2013
为了为此编写一个快速脚本,我引用了以下信息:
- 读取批处理文件中的 stdin 流
- 在批处理文件中执行子字符串的最佳方法是什么?
- 如何删除批处理文件中用户提供的输入的尾随和前导空格?
- DOS 批处理 - 函数教程提供了函数中参数传递的全面概述。
我想出了这个批处理脚本,ParamCSV.bat
:
@echo off
:: ParamCSV.bat
::
:: Usage: ParamCSV.bat <Parameter_ID> < history.txt
::
:: Thanks to:
:: https://stackoverflow.com/questions/6979747/read-stdin-stream-in-a-batch-file/6980605#6980605
:: https://stackoverflow.com/questions/636381/what-is-the-best-way-to-do-a-substring-in-a-batch-file
:: https://stackoverflow.com/questions/3001999/how-to-remove-trailing-and-leading-whitespace-for-user-provided-input-in-a-batch
:: Copy input parameter to 'id'
set id=%1
setlocal DisableDelayedExpansion
for /F "skip=2 tokens=*" %%a in ('findstr /n $') do (
set "line=%%a"
setlocal EnableDelayedExpansion
set "line=!line:*:=!"
set "activity=!line:~0,17!"
call:trim !activity! activity
set "status=!line:~17,11!"
call:trim !status! status
set "date=!line:~28,11!"
call:trim !date! date
echo(!id!,!activity!,!status!,!date!
endlocal
)
goto:EOF
::function: trim
::synopsis: Removes leading and trailing whitespace from a sting. Two
:: parameters are expected. The first is the text string that
:: is to be trimmed. The second is the name of a variable in
:: the caller's space that will receive the result of the
:: trim operation.
::
::usage: call:trim string_to_trim var_to_update
:: e.g. call:trim %myvar1% myvar2
::trim left whitespace
setlocal
set input=%~1
for /f "tokens=* delims= " %%a in ("%input%") do set input=%%a
::trim right whitespace (up to 100 spaces at the end)
for /l %%a in (1,1,100) do if "!input:~-1!"==" " set input=!input:~0,-1!
::return trimmed string in place
endlocal&set "%~2=%input%"
这里做了许多假设,如果其中任何一个更改或无效,脚本将中断:
GetHistory.bat
的输出具有宽度为 17、11 和 11 的固定宽度列。您没有提供两位数日期的示例,因此我假设日期是右对齐的。- 有两个标题行,我们在
for
语句中跳过了这两个行。
所有 - 输出行都针对同一 ID,因此只需要一个输入参数,并且它是所有 CSV 输出行中的第一个元素。