组合文件并在组合文件中添加文件名(或文件名中的时间戳)

时间:2016-11-29 10:37:14

标签: batch-file cmd

我有一个批处理脚本,它循环遍历目录中的一系列json文件并将它们组合在一起。它还在组合文件的开头和结尾添加了一个方括号,并在每个文件组合之间添加逗号(以形成Json数组)。

@echo off
setlocal enableDelayedExpansion
dir /b /s /a-d C:\JSON_LOADER\Pre_Processing_Files\JSON_FILE*.json >files.temp
call :read <files.temp
del files.temp
del /q C:\JSON_LOADER\Pre_Processing_Files\JSON_FILE*.json
exit /b

:read
set "file="
set /p "file="
if not defined file exit /b
for /f "delims=/ tokens=1-3" %%a in ("%DATE:~4%") do (
    for /f "delims=:. tokens=1-4" %%m in ("%TIME: =0%") do (
        set /a cnt=%%c-%%b-%%a-%%m%%n%%o%%p
    )
)
call :write >C:\JSON_LOADER\COMBINED\JSON_FILE-%date:~-4,4%%date:~-7,2%%date:~-10,2%-%cnt%.json
goto :read

:write
echo [
type "!file!"
echo(
for /l %%N in (2 1 10000) do (
 set "file="
 set /p "file="
 if not defined file goto :end
 echo ,
 type "!file!"
 echo(
)
:end
echo ]
exit /b

我想要做的是在组合文件中的每条记录的末尾添加每个文件的文件名。文件名包含将数据加载到SQL时所需的时间戳。样本文件名是;

JSON_FILE-20160816-104507.json

理想情况下,我只想捕获'20160816-104507'时间戳部分,但是我也会对完整文件名感到满意,因为我可以在SQL中处理这个文件名。对于上面的例子,我想补充一下;

,"Filename":"JSON_FILE-20160816-104507.json"

更复杂的是,我正在组合的每个.json文件都包含在花括号{}中。我要求我插入的文件名出现在每行的最后一个大括号之前。因此,例如,当前得到的组合文件的样本是;

[
{"object":"JSON_FILE","eventType":"CREATE","JsonId":12345}
,
{"object":"JSON_FILE","eventType":"CREATE","JsonId":123445}
,
{"object":"JSON_FILE","eventType":"CREATE","JsonId":123455}
]

我想将文件名信息(或文件名中的时间戳)附加到每条记录的末尾,但是在这个示例中的大括号内;

[
{"object":"JSON_FILE","eventType":"CREATE","JsonId":12345,"Filename":"JSON_FILE-20160816-104507.json"}
,
{"object":"JSON_FILE","eventType":"CREATE","JsonId":12345,"Filename":"JSON_FILE-20160816-104601.json"}
,
{"object":"JSON_FILE","eventType":"CREATE","JsonId":12345,"Filename":"JSON_FILE-20160816-104929.json"}
]

另一种选择,如果可能的话,是在通过FART组合之前运行文件,用,"Filename":"[filename]"}替换最后的花括号但是我不确定如何在递归查找中捕获文件名在应用程序中替换。

1 个答案:

答案 0 :(得分:0)

试试这个:

setlocal
  :: Set options
  set SourceFileFilter=JSON_FILE*.json
  set resultFile=result.txt

  ::Process each file
  echo [ > %resultFile%
  set IsFirst=1
  for %%i in (%SourceFileFilter%) do call :ProcessFile "%%i"
  echo ] >> %resultFile%

endlocal & goto:eof



:ProcessFile
setlocal
  :: THE FOLLOWING LINES ARE OPTIONAL, JUST TO GET TIMESTAMP (STORED IN LOCAL VARIABLE)
    set Timestamp=%~1
    set Timestamp=%Timestamp:JSON_FILE-=%
    set Timestamp=%Timestamp:.json=%
    echo The timestamp is stored in the local %%Timestamp%% variable: %Timestamp%
  :: END OPTIONAL

  :: Add "," if not the first processed file
  if NOT "%IsFirst%"=="1" echo ,>> %resultFile% 
  set /p JsonFile=<%1
  :: %JsonFile:}=% removes the } char
   echo %JsonFile:}=%,"Filename":"%~1"}>> %resultFile%

 :: End local environment, but before ending it, save IsFirst (as empty) for external usage, then exit
endlocal & set "IsFirst=" & goto:eof