Parse all text files in a folder using FOR /F command
Don't use /F
if you want to use a wildcard instead of a literal file-set. The differences of a "set" and a "file-set" are as follows, from FOR /?
FOR %variable IN (set) DO command [command-parameters]
...
(set) Specifies a set of one or more files. Wildcards may be used.
Versus
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
...
file-set is one or more file names. [note: no mention of wildcards]
If you want to glob all *.txt files, then wrap a FOR
around the outside:
FOR %A IN ( *.txt ) DO (
FOR /F "skip=2" %H IN ( %A ) DO (
ECHO %H 1>>Content.txt
)
)
Please be aware that your For /F "skip=2" %H
loop will read a file, one line at a time, then break the line into individual tokens using space or tab as a delimiter. Also from FOR /?
:
Each file is opened, read and processed before going on to the next file in file-set. Processing consists of reading in the file, breaking it up into individual lines of text and then parsing each line into zero or more tokens. The body of the for loop is then called with the variable value(s) set to the found token string(s).
That may not be your desired behavior. You can add a tokens=*
to grab all tokens in single variable. I'm also adding the option usebackq
so we can double quote the file-set in case any of the *.txt file names should contain a space:
FOR %A IN ( *.txt ) DO (
FOR /F "tokens=* usebackq skip=2" %H IN ( "%A" ) DO (
ECHO %H 1>>Content.txt
)
)
Arindam Banerjee
Updated on September 18, 2022Comments
-
Arindam Banerjee almost 2 years
There are numbers of txt file in a folder. Now I want to open all txt file and print the contents to a single txt file. Condition is, I want to skip first two lines of every txt file. I was trying with following command, but failed.
For /F "skip=2" %H IN (*.*) Do echo %H 1>>Content.txt
Error showing
The system cannot find the file *.*.
Same happened if I use
(.)
or(%1)
instead of(*.*)
.But if I mention the file names, then it works
For /F "skip=2" %H IN (aa.txt ab.txt ac.txt) Do echo %H 1>>Content.txt
What mistake I am doing.
-
gWaldo about 11 yearsWhile you can certainly do this in batch, I would recommend a higher-level language.
-
-
Arindam Banerjee about 11 yearsGreat. It worked. I misunderstood the FOR help.