- Is this possible to write list of file names into a text file using batch file Windows Xp?
- 3 Answers 3
- Not the answer you’re looking for? Browse other questions tagged batch-file cmd or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- How to copy a list of file names to text file?
- 6 Answers 6
- Print list of files in a directory to a text file (but not the text file itself) from terminal
- 5 Answers 5
- How to copy a directory structure but only include certain files (using windows batch files)
- 15 Answers 15
- File path formats on Windows systems
- Traditional DOS paths
- UNC paths
- DOS device paths
- Example: Ways to refer to the same file
- Path normalization
- Identify the path
- Handle legacy devices
- Apply the current directory
- Canonicalize separators
- Evaluate relative components
- Trim characters
- Skip normalization
- Case and the Windows file system
Is this possible to write list of file names into a text file using batch file Windows Xp?
I want to write the list of file names from a Given directory path in to text file whenever clicking a windows XP batch file.I don’t know whether it is possible or not in Windows Xp?
So,Can u please enlighten me on this?
3 Answers 3
How about something like this?
In a detailed way
If you want to list down all the file names with other details like time/size etc and no other directory information, you can use the below command
This will obtain a bare DIR format (no heading or footer info) but retain all the details, pipe the output of DIR into FIND .
This assumes that your date time stamp separator is : (e.g. 09-04-2018 11:06 ).
Not the answer you’re looking for? Browse other questions tagged batch-file cmd or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to copy a list of file names to text file?
How can I copy the names of files in a directory to a text file or to a clipboard?
6 Answers 6
It’s very, very easy in the Windows Command-Line Interpreter (all Windows OSes):
- Open a command prompt (Start -> Run -> cmd Enter )
- Navigate ( cd ) to the directory whose files you want to list.
- Enter dir >output_file_name (e.g., dir > C:\dir.txt ) and press Enter .
Open the newly created text file ( C:\dir.txt ) and you’ll have the complete output of the dir command in that directory.
The greater than symbol ( > ) signifies output redirection; it sends the output from most commands to a file you specify and is very handy for being able to log output from commands.
The output can be controlled with all the various options available for customizing the normal output of the DIR command; just add the output redirection at the end of whatever arguments you want to send that output to the text file.
Update: Creating a right-click context menu for creating directory contents listing
Create a batch file and save it as %windir%\DirList.bat :
Open your SendTo directory:
Windows 7/Vista: %appdata%\Microsoft\Windows\SendTo
Windows XP: %USERPROFILE%\SendTo
Create a new shortcut pointing to DirList.bat and call it whatever you please.
Now, right clicking on any directory and selecting the SendTo sub-menu will present your new command for listing directory contents.
NOTE: This will only work when right-clicking on a directory, and it will only list the contents of the directory you right-clicked on. It also saves the list to that directory (to avoid overwriting other files). The script could be easily modified to change where the output list file is stored.
Print list of files in a directory to a text file (but not the text file itself) from terminal
I would like to print all the filenames of every file in a directory to a .txt file.
Let’s assume that I had a directory with 3 files:
and I tried using ls > output.txt .
The thing is that when I open output.txt I find this list:
Is there a way to avoid printing the name of the file where I’m redirecting the output? Or better is there a command able to print all the filenames of files in a directory except one?
5 Answers 5
Note that this assumes that there’s no preexisting output.txt file — if so, delete it first.
printf ‘%s\n’ * uses globbing (filename expansion) to robustly print the names of all files and subdirectories located in the current directory, line by line.
Globbing happens before output.txt is created via output redirection > output.txt (which still happens before the command is executed, which explains your problem), so its name is not included in the output.
Globbing also avoids the use of ls , whose use in scripting is generally discouraged.
In general, it is not good to parse the output of ls , especially while writing production quality scripts that need to be in good standing for a long time. See this page to find out why: Don’t parse ls output
In your example, output.txt is a part of the output in ls > output.txt because shell arranges the redirection (to output.txt) before running ls .
The simplest way to get the right behavior for your case would be:
or, store the output in a hidden file (or in a normal file in some other directory) and then move it to the final place:
A more generic solution would be using grep -v :
How to copy a directory structure but only include certain files (using windows batch files)
As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure:
The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)?
The resulting directory structure should look like this:
15 Answers 15
You don’t mention if it has to be batch only, but if you can use ROBOCOPY , try this:
EDIT: Changed the /S parameter to /E to include empty folders.
An alternate solution that copies one file at a time and does not require ROBOCOPY:
The outer for statement generates any possible path combination of subdirectory in SOURCE_DIR and name in FILENAMES_TO_COPY . For each existing file xcopy is invoked. FILE_INTERMEDIATE_DIR holds the file’s subdirectory path within SOURCE_DIR which needs to be created in DEST_DIR .
try piping output of find (ie. the file path) into cpio
cpio checks timestamp on target files — so its safe and fast.
remove -v for faster op, once you get used to it.
If Powershell is an option, you can do this:
The main disadvantage is it copies all folders, even if they will end up being empty because no files match the filter you specify. So you could end up with a tree full of empty folders, in addition to the few folders that have the files you want.
Thanks To Previous Answers. 🙂
This script named «r4k4copy.cmd»:
It accepts variable of «Source», «Destination», and «FileName». It also can only copying specified type of files or selective filenames.
Any improvement are welcome. 🙂
To copy all text files to G: and preserve directory structure:
With find and cp only:
Similar to Paulius’ solution, but the files you don’t care about are not copied then deleted:
That’s only two simple commands, but I wouldn’t recommend this, unless the files that you DON’T need to copy are small. That’s because this will copy ALL files and then remove the files that are not needed in the copy.
Sure, the second command is kind of long, but it works!
Also, this approach doesn’t require you to download and install any third party tools (Windows 2000+ BATCH has enough commands for this).
Under Linux and other UNIX systems, using the tar command would do this easily.
Then you’d cwd to the target and:
Of course you could pipe the output from the first tar into the 2nd, but seeing it work in steps is easier to understand and explain. I’m missing the necessary cd /to/new/path/ in the following command — I just don’t recall how to do it now. Someone else can add it, hopefully.
Tar (gnutar) is available on Windows too, but I’d probably use the xcopy method myself on that platform.
EDIT: If you want to preserve the empty folders (which, on rereading your post, you seem to) use /E instead of /S.
Using WinRAR command line interface, you can copy the file names and/or file types to an archive. Then you can extract that archive to whatever location you like. This preserves the original file structure.
I needed to add missing album picture files to my mobile phone without having to recopy the music itself. Fortunately the directory structure was the same on my computer and mobile!
- C:\Downloads\music.rar = Archive to be created
- X:\music\ = Folder containing music files
- Folder.jpg = Filename I wanted to copy
This created an archive with all the Folder.jpg files in the proper subdirectories.
This technique can be used to copy file types as well. If the files all had different names, you could choose to extract all files to a single directory. Additional command line parameters can archive multiple file types.
For those using Altap Salamander (2 panels file manager) : in the Options of the Copy popup, just specify the file names or masks. Easy.
I am fine with regular expressions, lazy and averse to installs, so I created a batch file that creates the directory and copies with vanilla DOS commands. Seems laborious but quicker for me than working out robocopy.
- Create your list of source files with complete paths, including drive letter if nec, in a text file.
- Switch on regular expressions in your text editor.
- Add double quotes round each line in case of spaces — search string (.*) replace string «\1» , and click replace all
- Create two lines per file — one to create the directory, one to copy the file (qqq will be replaced with destination path) — search string (.*) replace string md qqq\1\nxcopy \1 qqq\1\n and click replace all
- Remove the filename from the destination paths – search \\([^\\^»]+)»\n replace \\»\n
- Replace in the destination path (in this example A:\src and B:\dest ). Turn OFF regular expressions, search qqq»A:\src\ replace B:\dest\ and click replace all.
md will create nested directories. copy would probably behave identically to xcopy in this example. You might want to add /Y to xcopy to suppress overwrite confirms. You end up with a batch file like so:
repeated for every file in your original list. Tested on Win7.
File path formats on Windows systems
Members of many of the types in the System.IO namespace include a path parameter that lets you specify an absolute or relative path to a file system resource. This path is then passed to Windows file system APIs. This topic discusses the formats for file paths that you can use on Windows systems.
Traditional DOS paths
A standard DOS path can consist of three components:
- A volume or drive letter followed by the volume separator ( : ).
- A directory name. The directory separator character separates subdirectories within the nested directory hierarchy.
- An optional filename. The directory separator character separates the file path and the filename.
If all three components are present, the path is absolute. If no volume or drive letter is specified and the directory name begins with the directory separator character, the path is relative from the root of the current drive. Otherwise, the path is relative to the current directory. The following table shows some possible directory and file paths.
Path | Description |
---|---|
C:\Documents\Newsletters\Summer2018.pdf | An absolute file path from the root of drive C: . |
\Program Files\Custom Utilities\StringFinder.exe | An absolute path from the root of the current drive. |
2018\January.xlsx | A relative path to a file in a subdirectory of the current directory. |
..\Publications\TravelBrochure.pdf | A relative path to file in a directory that is a peer of the current directory. |
C:\Projects\apilibrary\apilibrary.sln | An absolute path to a file from the root of drive C: . |
C:Projects\apilibrary\apilibrary.sln | A relative path from the current directory of the C: drive. |
Note the difference between the last two paths. Both specify the optional volume specifier ( C: in both cases), but the first begins with the root of the specified volume, whereas the second does not. As result, the first is an absolute path from the root directory of drive C: , whereas the second is a relative path from the current directory of drive C: . Use of the second form when the first is intended is a common source of bugs that involve Windows file paths.
You can determine whether a file path is fully qualified (that is, it the path is independent of the current directory and does not change when the current directory changes) by calling the Path.IsPathFullyQualified method. Note that such a path can include relative directory segments ( . and .. ) and still be fully qualified if the resolved path always points to the same location.
The following example illustrates the difference between absolute and relative paths. It assumes that the directory D:\FY2018\ exists, and that you haven’t set any current directory for D:\ from the command prompt before running the example.
If you would like to see code comments translated to languages other than English, let us know in this GitHub discussion issue.
UNC paths
Universal naming convention (UNC) paths, which are used to access network resources, have the following format:
- A server or host name, which is prefaced by \\ . The server name can be a NetBIOS machine name or an IP/FQDN address (IPv4 as well as v6 are supported).
- A share name, which is separated from the host name by \ . Together, the server and share name make up the volume.
- A directory name. The directory separator character separates subdirectories within the nested directory hierarchy.
- An optional filename. The directory separator character separates the file path and the filename.
The following are some examples of UNC paths:
Path | Description |
---|---|
\\system07\C$\ | The root directory of the C: drive on system07 . |
\\Server2\Share\Test\Foo.txt | The Foo.txt file in the Test directory of the \\Server2\Share volume. |
UNC paths must always be fully qualified. They can include relative directory segments ( . and .. ), but these must be part of a fully qualified path. You can use relative paths only by mapping a UNC path to a drive letter.
DOS device paths
The Windows operating system has a unified object model that points to all resources, including files. These object paths are accessible from the console window and are exposed to the Win32 layer through a special folder of symbolic links that legacy DOS and UNC paths are mapped to. This special folder is accessed via the DOS device path syntax, which is one of:
In addition to identifying a drive by its drive letter, you can identify a volume by using its volume GUID. This takes the form:
DOS device path syntax is supported on .NET implementations running on Windows starting with .NET Core 1.1 and .NET Framework 4.6.2.
The DOS device path consists of the following components:
The device path specifier ( \\.\ or \\?\ ), which identifies the path as a DOS device path.
The \\?\ is supported in all versions of .NET Core and .NET 5+ and in .NET Framework starting with version 4.6.2.
A symbolic link to the «real» device object (C: in the case of a drive name, or Volume
The first segment of the DOS device path after the device path specifier identifies the volume or drive. (For example, \\?\C:\ and \\.\BootPartition\ .)
There is a specific link for UNCs that is called, not surprisingly, UNC . For example:
For device UNCs, the server/share portion forms the volume. For example, in \\?\server1\e:\utilities\\filecomparer\ , the server/share portion is server1\utilities . This is significant when calling a method such as Path.GetFullPath(String, String) with relative directory segments; it is never possible to navigate past the volume.
DOS device paths are fully qualified by definition. Relative directory segments ( . and .. ) are not allowed. Current directories never enter into their usage.
Example: Ways to refer to the same file
The following example illustrates some of the ways in which you can refer to a file when using the APIs in the System.IO namespace. The example instantiates a FileInfo object and uses its Name and Length properties to display the filename and the length of the file.
Path normalization
Almost all paths passed to Windows APIs are normalized. During normalization, Windows performs the following steps:
- Identifies the path.
- Applies the current directory to partially qualified (relative) paths.
- Canonicalizes component and directory separators.
- Evaluates relative directory components ( . for the current directory and .. for the parent directory).
- Trims certain characters.
This normalization happens implicitly, but you can do it explicitly by calling the Path.GetFullPath method, which wraps a call to the GetFullPathName() function. You can also call the Windows GetFullPathName() function directly using P/Invoke.
Identify the path
The first step in path normalization is identifying the type of path. Paths fall into one of a few categories:
- They are device paths; that is, they begin with two separators and a question mark or period ( \\? or \\. ).
- They are UNC paths; that is, they begin with two separators without a question mark or period.
- They are fully qualified DOS paths; that is, they begin with a drive letter, a volume separator, and a component separator ( C:\ ).
- They designate a legacy device ( CON , LPT1 ).
- They are relative to the root of the current drive; that is, they begin with a single component separator ( \ ).
- They are relative to the current directory of a specified drive; that is, they begin with a drive letter, a volume separator, and no component separator ( C: ).
- They are relative to the current directory; that is, they begin with anything else ( temp\testfile.txt ).
The type of the path determines whether or not a current directory is applied in some way. It also determines what the «root» of the path is.
Handle legacy devices
If the path is a legacy DOS device such as CON , COM1 , or LPT1 , it is converted into a device path by prepending \\.\ and returned.
A path that begins with a legacy device name is always interpreted as a legacy device by the Path.GetFullPath(String) method. For example, the DOS device path for CON.TXT is \\.\CON , and the DOS device path for COM1.TXT\file1.txt is \\.\COM1 .
Apply the current directory
If a path isn’t fully qualified, Windows applies the current directory to it. UNCs and device paths do not have the current directory applied. Neither does a full drive with separator C:\ .
If the path starts with a single component separator, the drive from the current directory is applied. For example, if the file path is \utilities and the current directory is C:\temp\ , normalization produces C:\utilities .
If the path starts with a drive letter, volume separator, and no component separator, the last current directory set from the command shell for the specified drive is applied. If the last current directory was not set, the drive alone is applied. For example, if the file path is D:sources , the current directory is C:\Documents\ , and the last current directory on drive D: was D:\sources\ , the result is D:\sources\sources . These «drive relative» paths are a common source of program and script logic errors. Assuming that a path beginning with a letter and a colon isn’t relative is obviously not correct.
If the path starts with something other than a separator, the current drive and current directory are applied. For example, if the path is filecompare and the current directory is C:\utilities\ , the result is C:\utilities\filecompare\ .
Relative paths are dangerous in multithreaded applications (that is, most applications) because the current directory is a per-process setting. Any thread can change the current directory at any time. Starting with .NET Core 2.1, you can call the Path.GetFullPath(String, String) method to get an absolute path from a relative path and the base path (the current directory) that you want to resolve it against.
Canonicalize separators
All forward slashes ( / ) are converted into the standard Windows separator, the back slash ( \ ). If they are present, a series of slashes that follow the first two slashes are collapsed into a single slash.
Evaluate relative components
As the path is processed, any components or segments that are composed of a single or a double period ( . or .. ) are evaluated:
For a single period, the current segment is removed, since it refers to the current directory.
For a double period, the current segment and the parent segment are removed, since the double period refers to the parent directory.
Parent directories are only removed if they aren’t past the root of the path. The root of the path depends on the type of path. It is the drive ( C:\ ) for DOS paths, the server/share for UNCs ( \\Server\Share ), and the device path prefix for device paths ( \\?\ or \\.\ ).
Trim characters
Along with the runs of separators and relative segments removed earlier, some additional characters are removed during normalization:
If a segment ends in a single period, that period is removed. (A segment of a single or double period is normalized in the previous step. A segment of three or more periods is not normalized and is actually a valid file/directory name.)
If the path doesn’t end in a separator, all trailing periods and spaces (U+0020) are removed. If the last segment is simply a single or double period, it falls under the relative components rule above.
This rule means that you can create a directory name with a trailing space by adding a trailing separator after the space.
You should never create a directory or filename with a trailing space. Trailing spaces can make it difficult or impossible to access a directory, and applications commonly fail when attempting to handle directories or files whose names include trailing spaces.
Skip normalization
Normally, any path passed to a Windows API is (effectively) passed to the GetFullPathName function and normalized. There is one important exception: a device path that begins with a question mark instead of a period. Unless the path starts exactly with \\?\ (note the use of the canonical backslash), it is normalized.
Why would you want to skip normalization? There are three major reasons:
To get access to paths that are normally unavailable but are legal. A file or directory called hidden. , for example, is impossible to access in any other way.
To improve performance by skipping normalization if you’ve already normalized.
On .NET Framework only, to skip the MAX_PATH check for path length to allow for paths that are greater than 259 characters. Most APIs allow this, with some exceptions.
.NET Core and .NET 5+ handles long paths implicitly and does not perform a MAX_PATH check. The MAX_PATH check applies only to .NET Framework.
Skipping normalization and max path checks is the only difference between the two device path syntaxes; they are otherwise identical. Be careful with skipping normalization, since you can easily create paths that are difficult for «normal» applications to deal with.
Paths that start with \\?\ are still normalized if you explicitly pass them to the GetFullPathName function.
You can pass paths of more than MAX_PATH characters to GetFullPathName without \\?\ . It supports arbitrary length paths up to the maximum string size that Windows can handle.
Case and the Windows file system
A peculiarity of the Windows file system that non-Windows users and developers find confusing is that path and directory names are case-insensitive. That is, directory and file names reflect the casing of the strings used when they are created. For example, the method call