批处理:检查空值并在其位置写入字符串

时间:2016-11-17 17:59:49

标签: batch-file

我有一组包含一行数据或空白的文本文件。我需要将所有这些文件转储到一个文件中。这部分很容易,但我需要空白文件在新文件中返回“Nodata”或类似的字符串。

setlocal enabledelayedexpansion
type nul >C:\somedirectory\DataAll.txt


REM Find all files in a direcotry; for those files
for %%G in (C:\somedirectory\txt??.txt) do (
REM Find all of the text within the found files
for /f "tokens=*" %%T in ('type "C:\somedirectory\%%~nG.txt"') do (
set DataIn=%%T
    REM Check to see if the file is empty and write NoData the final variable to it if so
    if "C:\somedirectory\%%~nG.txt" LSS 1('set "/a DataIn=Nodata"')
    REM Check to see if file is not empty and write the data to the final variable 
    if "C:\somedirectory\%%~nG.txt" NEQ 0 ('set /a "DataIn=%%T"')
    REM Write DataIn to final text file
    >> "C:\somedirectory\DataAll.txt" echo !DataIn!
)   
)

endlocal

这会将之前的文本文件数据复制到空白文件中。例如,如果txt1有xxx,xxx,xx; txt2是空白的;和txt3是x,x,x,datall文件将读取:

  

XXX,XXX,XX

     

XXX,XXX,XX

     

X,X,X

如何将DataIn设置为另一个字符串?

1 个答案:

答案 0 :(得分:1)

for %%G in (C:\somedirectory\txt??.txt) do (
 set "DataIn=No data"
 REM Find all of the text within the found files
 for /f "usebackqtokens=*" %%T in ("C:\somedirectory\%%~nG.txt") do (
  set DataIn=%%T
 )
 REM Write DataIn to final text file
>> "C:\somedirectory\DataAll.txt" echo !DataIn!
)

依赖于“它是空白或有1行”信息,然后将输出字符串datain设置为“未找到”值,并用一条数据线覆盖它(如果已找到)。空文件不会执行do循环的for %%T部分。