Click here to Skip to main content
15,885,278 members
Articles / Operating Systems / Windows
Tip/Trick

A DOS One-Liner: Running a Program Against a List of Files

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
24 Apr 2018CPOL5 min read 7.5K   8   2
Run many (hundreds, even) files through a program or script, using nothing but CMD.EXE.

Introduction

Yesterday, I needed to run a character mode program that takes a single file name or mask against all files in a directory tree. Since the program in question doesn't support directory recursion out of the box, and I didn't want to take the time to modify it, I devised an alternative strategy based on using a for loop to process a list of file names. Though I've used such loops in batch files for many years, and I was aware that they can be run as one-line commands, this was the first use case I've had that fairly begged for this approach.

Background

Using for loops to process lists is not exactly new, and I've been doing so for at least the last 20 years, more so in recent years than in the distant past. Since most of the command line programs that I use regularly support subdirectory recursion out of the box, I haven't had much need for this capability. Two things made this an outstanding use case.

  1. The directory tree is quite large.
  2. There were whole subdirectories that needed to be excluded.

Even if the comand line tool in question supported directory recursion, the requirement to exclude whole directories would have prevented its use, leaving me in search of another option. Enter the humble for loop, in the form of a one-line shell command.

Using the code

Thanks to the underrated /b switch, generating the preliminary file list is straightforward, 

BAT
dir F:\Praesidium_SVN\ALTPS\admin\*.js /b /s > F:\Praesidium\Armatus_Admin_EventRegistration\_Stories\DT_563\JavaScript_Inventory_ArmatusAdmin.TXTL

Let's take this apart.

  • dir F:\Praesidium_SVN\ALTPS\admin\*.js /b /s is a straightforward request for a recursive directory listing. It uses two switches.
    • /b is the Bare Listing switch, which causes dir to list only the file names, one file per line.
    • /s is the Subdirectory Recursion switch, which cause dir to look through all subdirectories of the specified top level directory for names that match the file specification.
    • F:\Praesidium_SVN\ALTPS\admin\ names the top level directory.
    • *.js is the file name mask.
  • > is the pipe directive, which redirects output that would have displayed on the command prompt window elsewhere. In our case, elsehwere is a file, though it could as well be the standard input (console input) of another program, such as more.exe.
  • F:\Praesidium\Armatus_Admin_EventRegistration\_Stories\DT_563\BabelRC_Inventory_ArmatusAdmin.TXT is the name to give to a new file that receives the output of the dir command.

F:\Praesidium\Armatus_Admin_EventRegistration\_Stories\DT_563\JavaScript_Inventory_ArmatusAdmin_20180423_133355.TXT is a list of every JavaScript file in directory F:\Praesidium_SVN\ALTPS\admin and its subdirectories. However, since the application uses locally installed Node/JS packages, it has an enormous node_modules directory that is irrelevant, and adds significant processing time. (For reasons that have relatively little bearing on the topic at hand, there are actually two node_modules directories in this tree.) Pruning the list is straightforward; open your favorite text editor, and eliminate them from the list. Since the files are listed alphabedically by directory, finding and eliminating the unwanted directories is a cinch.

It's Showtime

BAT
for /f "tokens=*" %F in ( F:\Praesidium\Armatus_Admin_EventRegistration\_Stories\DT_563\JavaScript_Inventory_ArmatusAdmin.TXT ) do encoding show %F >> F:\Praesidium\Armatus_Admin_EventRegistration\_Stories\DT_563\JavaScript_Encodings_ArmatusAdmin.TXT

Let's take this apart.

  • for /f "tokens=*" %F in sets up the for loop to process a text file composed of lines, each of which contains the name of a file.
    • /f tells for that the list it is receiving is a list of file names.
    • %F is a subsitution token, which is replaced in turn by each file name in the list in the command that comprises the body of the for loop. Note the use of a single % character, unlike the doulbe % used in batch files.
  • ( F:\Praesidium\Armatus_Admin_EventRegistration\_Stories\DT_563\JavaScript_Inventory_ArmatusAdmin.TXT ) is the list, comprised in this case of the edited text file that I just described.
  • do encoding show %F is the one-line body of the for loop.
    • encoding is the program or command to run. encoding is a compiled Python script that attempts to identify the text encoding of one or more text files.
    • show is a directive to encoding , which instructs the program to show the cureent encoding. The program offers other options for changing the encoding.
    • %F is the substitution token, which is replaced on each iteration with the name of a file to process.
  • >> F:\Praesidium\Armatus_Admin_EventRegistration\_Stories\DT_563\JavaScript_Encodings_ArmatusAdmin.TXT is a slightly different output redirection instruction that sends the voluminous output of the loop into a text file for subsequent review, Note again the use of a single % character.
    • >> is a different redirecton symbol; which directs the shell to append to the specified file. Since the command repeats many times, this is required to preserve output from previous iterations. Since a regular redirection (>) creates a new file, it would preserve only the output of the last iteration.
    • The rest of the string is the name to give to the output file.

Hit Enter, sit back, and watch your DOS one-liner run.

Points of Interest

Encoding.exe, the program around which I built this wonderful one-liner, is worthy of attention in its own right, since it works really well, and can be handy for just such use cases as I faced, where I needed to verify that none of the files in two collecitons was UTF-8 encoded.

For many years, I've heard and read about Perl one-liners, and I've used some, and even written a few of my own. Along the same lines, I've read about PowerShell and Bash one-liners. However, this is the first of what I think qualfies as a DOS one-liner.

I put spaces around all special tokens, such as the parentheses that enclose the list and the pipe direcitve. Though technically optional, they make the command much easier to read and deciper.

Bear in mind that if the command that follows do is a batch (.CMD or .BAT) file, its name must be preceded by call. Otherwise, the first invocation would never return to the loop, and only the first file would get processed.

History

Tussday, 24 April 2018 marks the initial publication of this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
I deliver robust, clean, adaptable, future-ready applications that are properly documented for users and maintainers. I have deep knowledge in multiple technologies and broad familiarity with computer and software technologies of yesterday, today, and tomorrow.

While it isn't perceived as sexy, my focus has always been the back end of the application stack, where data arrives from a multitude of sources, and is converted into reports that express my interpretation of The Fundamental Principle of Tabular Reporting, and are the most visible aspect of the system to senior executives who approve the projects and sign the checks.

While I can design a front end, I prefer to work at the back end, getting data into the system from outside sources, such as other computers, electronic sensors, and so forth, and getting it out of the system, as reports to IDENTIFY and SOLVE problems.

When presented with a problem, I focus on identifying and solving the root problem for the long term.

Specialties: Design: Relational data base design, focusing on reporting; organization and presentation of large document collections such as MSDS libraries

Development: Powerful, imaginative utility programs and scripts for automated systems management and maintenance

Industries: Property management, Employee Health and Safety, Services

Languages: C#, C++, C, Python, VBA, Visual Basic, Perl, WinBatch, SQL, XML, HTML, Javascript

Outside Interests: Great music (mostly, but by no means limited to, classical), viewing and photographing sunsets and clouds, traveling by car on small country roads, attending museum exhibits (fine art, history, science, technology), long walks, especially where there is little or no motor traffic, reading, especially nonfiction and thoughtfully written, thought provoking science fiction

Comments and Discussions

 
SuggestionTypo in this Pin
lopatir26-Apr-18 2:26
lopatir26-Apr-18 2:26 
QuestionBringing back memories, but you can eliminate the editing step... Pin
Kirk 1038982125-Apr-18 8:07
Kirk 1038982125-Apr-18 8:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.