0

How to open all the text files (.txt) In a directory , which have some data in it (size not 0 ) using batch script.

Thanks in advance.

Manas Mohanta
  • 65
  • 1
  • 1
  • 4

2 Answers2

4
for %%a in ("c:\folder\*.txt") do if %%~za gtr 0 start "" "%%~fa"

The for command will iterate over the files matched by the in clause. For each file found, the code in the do clause is executed with a reference to the file stored in the replaceable parameter (%%a in this sample)

%%~za is the size of the file and %%~fa is the file reference with the full path. So, the code means: for each txt file in the indicated folder, if the size of the file is greater than 0, start the file with whatever application associated to it

note: start command takes the first quoted argument as the title of the started window. As the file reference is quoted to prevent problems with spaces, the empty quotes are included to avoid the file reference being readed as a title

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Don't know why but `in ("c:\folder\*.txt")` does not work for me (`Win8.1`) from command line, shows only one file. Using `in ('dir /b "c:\folder\*.txt"')` shows all files but no `~z` modified values except last file in list. Have to use `in ('dir /b /s "c:\folder\*.txt"')` – JosefZ Jan 29 '15 at 07:20
  • 1
    @JosefZ, If i have to bet, you are including an `/f` to the `for` command that is not included in my code. – MC ND Jan 29 '15 at 07:47
  • Yes, I see that `/f` was a culprit (in my head). You are right with `for %%a in ("c:\folder\*.txt") do ...`. However, `for /F "tokens=*" %I in ('dir /B "c:\folder\*.txt"') do @echo %~fI %~zI %~tI` shows filenames only, no file size and time as expected. With `dir /B /S` it works. – JosefZ Jan 29 '15 at 08:19
  • There is a new question about the same problem: [DOS Batch File Variable Modifier Returns Blank](http://stackoverflow.com/q/28203010/3439404) so I will switch there ^Z – JosefZ Jan 29 '15 at 09:31
  • 1
    @josefz, `for /f` processes text. If your current active directory is not the indicated in the `in` clause of the `for`, as the `dir /b` only returns the file name, if you try to obtain the size of the file (that is in another folder) it will fail (blank value) as the file is not found. The aditional `/s` makes the `dir` command include the full path to the file, so, now the file is found and the size returned – MC ND Jan 29 '15 at 10:18
  • Bingo! Again, the reason lays in my dumb head, as per usual... :) Thank you! Please, give it as an answer to the question mentioned above. – JosefZ Jan 29 '15 at 10:29
0

This will explain how to loop files in a batch file and conditionally do something based on file size.

How can I check the size of a file in a Windows batch script?

You can then modify it to use notepad or another program to open the file.

Community
  • 1
  • 1
eyegropram
  • 672
  • 4
  • 11