Windows批处理脚本:从文本文件中获取特定列下的值

时间:2017-07-12 20:17:24

标签: windows batch-file

我有一个包含多列的文本文件

Column1 Column2 Column3 AS_OF_DATE
1        2       3      07/12/2017
2        3       4      07/12/2017
.....

n行数 AS_OF_DATE表示文本文件中数据的日期。对于所有行都是相同的.AS_OF_DATE列的位置可以在任何位置。 现在我的要求是在AS_OF_DATE列下选择日期并将其存储在单独的文件中。

对此有所帮助。

由于 KVB

1 个答案:

答案 0 :(得分:2)

此代码对您的数据做出了许多假设:

  • 标题行中没有*?个字符
  • 标题行中没有&|等毒害字符
  • 列名称或列值中没有空格
  • 所有列都已完全填充
  • 您的输入文件使用标准的Windows行结尾或<CR><LF>,而不是<LF>的结尾

可能还有其他我不记得的限制

@echo off
setlocal

:: Define files
set "input=test.txt"
set "output=out.txt"

:: Read first (column header) line
<"%input%" set /p "ln="

:: Figure out which column contains AS_OF_DATE
for /f "delims=:" %%N in (
  'cmd /c "(for %%C in (%ln%) do @echo %%C)|findstr /n AS_OF_DATE"'
) do set "col=%%N"

:: Write all AS_OF_DATE values to a new file
>"%output%" (
  for /f "skip=1 usebackq eol= tokens=%col%" %%A in ("%input%") do echo %%A
)

更新: 以下是仅读取前2行的修改

@echo off
setlocal

:: Define files
set "input=test.txt"
set "output=out.txt"

:: Read the first two lines
<"%input%" (
  set /p "header="
  set /p "data="
)

:: Figure out which column contains AS_OF_DATE
for /f "delims=:" %%N in (
  'cmd /c "(for %%C in (%header%) do @echo %%C)|findstr /n AS_OF_DATE"'
) do set "col=%%N"

:: Extract the AS_OF_DATE value and write to a new file
for /f "skip=1 eol= tokens=%col%" %%A in ("%data%") do >"%output%" echo %%A