How to Batch Append Filename to TXT Contents, Name Output File Based on Original Input Filename, and Loop Through 200,000 Input Files

这一生的挚爱 提交于 2019-12-12 02:43:37

问题


I am working on an HR data project and after much research and even more trial and error, I have adapted the following Batch File (Windows 8.1 environment) that successfully pulls an employee’s start date from a messy text file - with many thanks to user dbenham for that prior solution (again which I adapted as follows):

@echo off
setlocal disableDelayedExpansion
set "cnt=1"
>OUTPUT.txt (
  for /f "skip=219 tokens=24,25,26 delims= " %%B in (MVANHOUTEN.txt) do (
    echo(%%B %%C %%D
    set /a "1/(cnt-=1)" 2>nul || goto :break
  )
)
:break

Where MVANHOUTEN.txt is the input file

OUTPUT.txt file contains only: January 21, 1991

I have a limited understanding of the intricacies of batch file programming, and despite the genius of dbenham's code which I have confirmed works 100% with my changes above, I do not know enough to alter this without breaking it. I need this batch file to do three more things but I cannot seem to make it work without destroying the functionality of the above code. Specifically, I need to:

  1. I need to add the original text filename to the contents of the output file after the data extract. That is, I need my output file to contain: MVANHOUTEN January 21, 1991
  2. Instead of OUTPUT.txt, I need my output file to be named with the same filename as the input file – that is, MVANHOUTEN.txt. If this is not possible or too unweildy, adding to the original filename would be an okay alternative – e.g. MVANHOUTEN-Processed.txt)
  3. I need a do loop as I have a directory of nearly 200,000 current and former employees and I need to batch perform the above operations for each and every file - so logically in place of "(MVANHOUTEN.TXT)" in the above, I need to find a way to loop through many *.txt files in the same directory. The results would be separate files MVANHOUTEN.txt, CMONTYBURNS.txt, DISCOSTU.txt, etc. etc. (or MVANHOUTEN-Processed.txt, CMONTYBURNS-Processed.txt, DISCOSTU-Processed.txt, etc.).

Can anybody please help me enhance my batch file above to accomplish the above without breaking the original scrub I successfully adapted from dbenham? Many thanks in advance!


回答1:


untested, as I don't have your datafiles:

@echo off
setlocal disableDelayedExpansion

for /f "delims=" %%a in ('dir /b *.txt') do (
  call :process %%a
)

:process
set "cnt=1"
>"%~n1-Processed.txt" (
  for /f "skip=219 tokens=24,25,26 delims= " %%B in (%~nx1) do (
    echo( %~n1 %%B %%C %%D
    set /a "1/(cnt-=1)" 2>nul || goto :eof
  )
)


来源:https://stackoverflow.com/questions/44464497/how-to-batch-append-filename-to-txt-contents-name-output-file-based-on-original

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