A Command Line Text Find and Replace Utility
Procon Construction Systems
WHAT IS FR?FR Command Line Text Find and Replace is a Windows' Console program designed to simplify find and replace text changes in sets of Microsoft Visual Studio Project files, other files organised in directory trees, or just single files.
FR is primarily designed for programmers - who want to change class, function or identity names in many source files; and web designers - so that they can automate coordinated changes to the many files comprising large websites.
FR allows you to:-
FR does not support:-
FR will automatically:-
FR FileSpec(s) FindText ReplText
FileSpec = the target File(s) - or file list of files.
The target can contain multiple wildcards.
(File list files must be preceded with @)
FindText = the text to find - or a file list of
matching Find/Replace pairs.
ReplText = the replacement text
Optional Switches: (following Repltext)
/I (or /IGNORECASE or /INSENSITIVE) = Ignore case
/C (or /CASESENSITIVE) = Case sensitive (default)
/W (or /WHOLE or /WORD) = Whole word match (default)
/P (or /PARTIAL) = Part word match
/D (or /DIRECTORY) = file directory only (default)
/S (or /SWEEP or /SUBDIRECTORIES) = include Subdirectories
/Q (or /QUIET) = Quiet output (mimimise messages)
/L (or /LINES) = Show Changed Line Numbers and Text
/M (or /MEF) = lines in MS Editor clickable format
/O (or /OVERWRITEBAK) = Overwrite old backup files
/N (or /NOBAK) = do Not create backup files
/E (or /ESCAPESEQ) = using character Escape sequences
/B (or /BINARY) = process Binary files without warning
/V (or /VS) = Process Visual Studio Project Files
/G = iGnore text within quoted strings
/X = eXclude text within C/C++ comments
/A (or /APPEND) = Append to log file (don't overwrite)
/K = do not Keep a log file
/T (or /TEST) = Test (list matches without replacing)
/F (or /FINDONLY) = Find only (do not provide repltext)
/? (or /HELP) = a basic HELP screen
Default: Case SENSITIVE, WHOLE WORD match, NO Subdirectories.
FR *.cpp ID_XYZ ID_ABC
FR *.cpp ID_XYZ /F /S
FR *.txt "quick fox" "lazy dog" /i
FR \SRC\*.cpp "CString str" "CXString str" /s /w
FR *.dsp;*.vcproj "unsigned int" "UINT" /I /Sub /VS
FR @Files.LST www.old.com www.newurl.com /I /P /S
FR @C:\VS\VCFiles.LST "//TODO:" "" /case /part /Sweep
FR "*.c*;*.h*" "@FR Pairs.LST" /Case /MEF /Sub /Quiet
FR *.cpp bool
FR requires a minimum of TWO command line parameters:-
The FIRST parameter
May be a single full path name or several pathnames separated by
commas or semi-colons and may contain wildcards. It is usually a file specification. For example:-
Pathnames with embedded spaces must be quoted.
If preceded by an '@' sign the parameter refers to a "File list" file. These @Files are plain text files containing a list of filenames to be processed - with one pathname per line. For example:-
//================ sample @File lines ==================== ; Note: Blank lines, or lines starting with a semicolon or // two forward slashes are ignored or treated as comments. INDEX.TXT Content\Chapter*.TXT E:\Webs\Personal\*.htm ..\..\Classes\XCustom\*.cpp // Lines can contain multiple masks or even other @Files *.TXT;*.ASC //==================== End of File =======================
Each pathname is treated as if it were entered on the command line. (The @File is then equivalent to creating a batch file to process each of the file specifications in turn.)
Processing may include files in subdirectories - or refer to MS Visual Studio Project file(s) which then causes all source files referenced in the project file(s) to be searched. It can also cause the same file to be processed several times (e.g., a header file included in several different Visual Studio projects).
These multiple levels of indirection - combined with wildcarding - can include many files in the search from just one invocation on the program.
If in doubt, use the /TEST flag before making permanent changes. (Although backup files are automatically created, restoring several thousand files is no small job. Changes are not always reversible by just switching find and replace text!)
The SECOND parameter
The text to find. If it contains embedded spaces - or any of the command line redirection or piping characters (i.e.,
<> or |) it MUST be quoted. So use
"Hello World!" not Hello World! and
"(m_nOffset<<2)" not (m_nOffset<<2).
When prefixed with an '@' sign, the parameter refers to a "Pair list" file. These are plain text files containing multiple Find and Replace pairs to be processed - with one pair per line. For example:-
//========== sample @Pair list file lines ============= ; Each line has matching find/replace pairs like this:- "Find this text" "replace it with this" "unsigned long " "UNLONG " char TCHAR "const char *" LPCTSTR "char *" LPTSTR \r \r\n //=================== End of File =====================
The THIRD parameter
The replacement text. Like the find text it must be quoted if it contains special characters. (If "" - a blank string - is used then the find text is replaced with nothing, i.e., removed.)
If a find/replace @Pair List File is specified (see above) do not provide a third replacement text parameter as it is ignored. Otherwise, when replacement text is not provided (the third parameter is missing or is preceded with a "switch" character) FR runs in "find" mode and does not make replacements.
Quote ALL filename and text parameters ALL the time. It avoids problems caused by "parameter shifting" if you inadvertently include spaces or special characters in filenames or find text.
Switches follow the replacement text parameter. The switch prefix can be a forward slash (/) or (for Unix fans) a minus sign (-).
All switches can be abbreviated to just one character.
Switches are read from left to right. So if repeated or contradictory switches are found the last switch effectively overrides the others. Hence you can set up a batch file to run FR with preferred switches and call the batch file with added qualifiers.
Text Case switches
/IGNORECASE or /INSENSITIVE
Match case insensitively (XYZ will match xyz, Xyz)
Match case sensitively (XYZ will NOT match xyz, Xyz)
Word Match switches
/WHOLE or /WORD
Whole word match (INT will NOT match LINT or INTEGER)
This is the default behaviour.
Part word match (INT matches POINT, INTEGER and LINT)
/SWEEP or /SUBDIRECTORIES
Include matching files in all Subdirectories of target (A path specification
D:\C\*.h will include ALL header files in
Only include matching files from the directory obtained from the FileSpec pathname.
Parse Microsoft Visual Studio Project Files to develop a list of source files to process. (.DSP and .VCPROJ files contain lists of all the files within a project. Visual Studio 6.x project files use a .DSP extension. Visual Studio 7.x files have a different format and use the extension .VCPROJ).
Note that this switch is normally an alternative to /SWEEP. However, both switches may logically be used together if @Files are specified. All matching @Files in all subdirectories will be parsed for DSP/VCPROJ files. Matching project files are parsed for source files which then become the find/replace targets. This double indirection may involve many target files. Only do this when you know what you are doing!!
Using Character Escape Sequences. Set this flag if the FindText or ReplText contains C/C++ Style Character Escape Sequences to match non-printable characters like Carriage Return ('\r'), Line Feed ('\n'), Horizontal Tab ('\t') etc. (The switch implies a binary file so the /BINARY switch is set automatically.)
FR supports an extended set of Escape Sequences such as:-
NL or LF
Double Quote Mark
Single Quote Mark
(This is basically the standard C/C++ escape set. It excludes the binary NUL character but adds a Decimal number option.)
For more information on standard Escape Sequences see:-
Using the /E flag we could convert a standard MS-DOS/Windows text file (lines are terminated with a CR/LF pair) to a Unix style text file (lines are terminated with just a LF) with the following command:-
FR *.TXT "\r\n" "\n" /E
and convert the other way with:-
FR *.TXT "\n" "\r\n" /E
Process Binary files WITHOUT warning. Caution! Some binary files will still be skipped but this should only be done after you are SURE no damage will result.
Force overwrite of existing backup files. If a .BAK file already exists it will be overwritten each time FR is run and saves a changed version of a target file. (Normally an existing backup file will NOT be overwritten so preserving an original copy of the file even if FR is run several times to make repeated changes).
"Quiet" output mode.Minimise the number of progress messages. Details on files skipped etc., will not be shown and the information written to the log file is much more compact. Use this ONLY when you are completely familiar with the program.
Show Changed Line Numbers and Text. List any changed lines with their line numbers.
Use the "Microsoft Editor format" to output changed lines. If the output is then directed to a compatible editor's debug window, you can left click on the line - or press <Enter> when the caret on the line - and the editor will open the referenced file at the designated line number. Format is:- FilePathName(nnn) : Line Text
List number of matches in each file but do not change any files. A good precautionary step before making changes to many files.
Operate in find mode only. Ignores any replacement text parameter provided..
Append output to log file rather than overwriting the log file each time FR runs. Useful when you wish to run FR several times - perhaps from a batch file - and want a complete record of all changes made.
Ignores find text inside double quotes. In source files, string literals are often enclosed in quotation marks, For example, a C/C++ string might look like this:-
const char szMsg = "This is a string literal";
This switch excludes text within quotes from the search.
Ignores find text inside 'C' and 'C++' comments. Hence a search for the word "this" through a file containing:-;
// assign instance to this;
*this = acXyz; /* this is C style comment */;
would ignore the first and third occurrences.
The /G and /X switches are designed to be used on C/C++ source and header files. They produce nonsensical results if applied to files that are not program source files and can give incorrect error and alert messages on other types of program files. The processing takes no account of preprocessor macro substitutions and just attempts to match "unescaped" quote and comment pairs to determine context. This is obviously subject to error.
Applying either of these switches forces FR.EXE to perform a basic check on the comments and strings within target files. In doing so it may issue alerts or warnings. Some examples:-
Alert: 'Start Comment' tokens '/*' within String!
Alert: 'End Comment' tokens '*/' within String!
Alert: Backslash EOL Continuation token \ within String!
Warning: New Line within String!
"Alert" messages flag valid - but unusual or deprecated - constructs.
"Warning" messages may indicate invalid code..
FR will operate as just a "Find" utility if the /FINDONLY switch is used or no replacement text parameter is provided on the command line.
If only the file path and find parameters are provided, the search will default to Partial match, /MEF line format and /QUIET mode. If the find text is mixed or upper case, the search will be case sensitive. Otherwise it will be case insensitive.
Most Text "find" utilities do not work reliably on binary files as they cannot search past embedded binary NULs and other non ASCII bytes.
Using "find and replace" utilities on binary files is dangerous as edits - particularly if they change the file length - will often destroy them.
However, with care and common sense, it is possible to edit SOME binary files without damaging them. Doing so can provide a quick way of updating these files.
FR does allow you to replace text in some binary files while providing some safeguards while doing so.
Certain binary files (identified by file extension), such as image files and specific Visual Studio temporary files, will be skipped. It is either ineffective or unnecessary to edit these files directly.
Other binary files - identified by an examination of their content - will be flagged as binary with a warning. This warning will be more severe if the text replacement would cause changes in the file length as this is more likely to be destructive.
The decision to proceed with the edit is yours - as is the responsibility for knowing whether the particular file can be safely edited!
FR output messages can be redirected to a device or a file using the standard command line redirection commands (e.g.,
FR /Help > HELP.TXT
will copy the basic help screen to the file HELP.TXT).
However, redirection can be complicated by the occasional need for user confirmation after errors or warnings. For this reason the utility automatically creates a log file - FR.LOG - in the current directory.
The log file saves a copy of all messages and prompts and the user's response. This can be useful in determining which files have been modified.
FR automatically creates a backup before changing any file. The backup is created in the same directory as the original file. The backup copy will have the same filename as the original with '.BAK' appended.
Hence if a target file named:-
is to be modified by FR, it will first be copied to a file named:-
If a backup file with that name already exists, no new backup is made. Hence, you can make repeated changes to a file without the backup being overwritten each time FR is run.
This behaviour can be overridden with the /OVERWRITEBAK switch.
VISUAL STUDIO TOOLS
FR can be used in conjunction with Visual Studio in various ways. One example is as a Project Find Tool that - unlike the built in Find Command - does not depend upon all documents being open.
To do this in Visual Studio 6.0, select Customize, Tools. The Customize dialog box appears.
Move to the end of the "Menu Contents" list and add "VSFin&d". Complete the other fields as follows:-
Command: F:\UT\FR.EXE (the path to FR.EXE)
Arguments: *.dsp;*.vcproj "$(CurText)" /Ins /Find /Me /VS /Quiet
Initial Directory: "$(WkspDir)"
Check the "Use Output Window" box and click "Close". This adds a new tool to the VS Tools Menu and a new VSFind tab to the Output window.
The VS Tool Window Customization Dialog looks like this:-
For more information, see "Customizing the Tools Menu" on the Microsoft Visual Studio 6.0 support site.
A Toolbar Icon should be created to allow single click and hotkey access to VSFind. (Customization, Commands, Category, Tools, and click and drag the appropriate tool icon to a toolbar or menu bar).
Place the caret on a word - or select some text - and click the VSFind icon. The Output, VSFind window will list locations where the selected text occurs in the project. The window might look like this:-
Click on any file/line indicator in this window to open a file at the line where text was found.
FR is designed to be easily enhanced with batch files. Many FR options are controlled by command line switches, so you can set preferred defaults by running the program from a batch file. If the batch file also passes parameters to FR these defaults can be overridden as required.
A number of sample batch files are included in the program archive.
This program uses several Windows' DLL files. If these are not present you will get an error message indicating which DLL is missing.
If this occurs, download the required DLLs from the links given in:- http://www.procon.com.au/UtilDLLs.htm
Use this utility at your own risk! If you do not understand
you can only cause yourself grief!. For example, you should fully understand why:-
shows a help screen and program version number.
Download the latest version of FR from Procon's Website.
Copyright 2004 - Procon Construction Systems
All Rights Reserved