This page documents the free, open-source program pgn-extract, which is designed to support the processing, searching and extraction of chess games from files written in PGN format. There are several ways to specify the criteria on which to extract: textual move sequences, the position reached after a sequence of moves, information in the tag fields, and material balance in the ending. Full ANSI C source and a 32-bit Windows binary for the program are available under the terms of the GNU General Public License. The program includes a semantic analyser which will report errors in game scores and it is also able to detect duplicate games found in one or more of its input files.
The range of input move formats accepted is fairly wide and includes recognition of lower-case piece letters for English and upper-case piece letters for Dutch and German. The default output is in English Standard Algebraic Notation (SAN), although there is some support for output in different notations.
Extracted games may be written out either including or excluding comments, NAGs, and variations. Games may be given ECO classifications derived from the accompanying file eco.pgn, or a customised version provided by the user.
Plus, lots of other useful features that have gradually found their way into what was once a relatively simple program!
There follows a brief summary of the different flags taken by pgn-extract, such as is produced by the -h flag. However, you are strongly advised to read the remainder of this file before attempting to use pgn-extract in earnest.
pgn-extract takes an arbitrary number of game scores as input and outputs zero or more of these games, typically in English Standard Algebraic Notation (SAN). Which of the input games are output, and the style of the output, depend upon the particular set of command line flags passed to pgn-extract. The general form for calling pgn-extract is as follows:
pgn-extract [flags] [input-game-files]
In its simplest form, calling pgn-extract with no arguments will cause it to read games from its standard input, check them and reproduce those without errors in SAN notation on its standard output.
This program's principle aim is to be able to read PGN files and output games of interest. It follows that the input should look reasonably like PGN to start with. This means that it doesn't cope well with files that contain news article or mail headers, for instance, although it does make an attempt to skip text that is obviously not game related between games. Having said that, it does not require the move text be in Standard Algebraic Notation (SAN). It will accept quite a few common formats including:
It does not require that there be any move numbers or PGN headers preceding a game, as long as the move text is terminated by a valid result designation: *, 1-0, 0-1, 1/2-1/2 (1/2 is also accepted). This makes the program reasonably suitable for entering raw game text and having it reformatted in proper SAN with a full set of headers.
Normally, the input files from which games are to be extracted are listed on the command line:
pgn-extract file1.pgn [file2.pgn ...]
An alternative to listing the game files on the command line is to list their names, one per line, in a file which is then given after the -f flag:
pgn-extract -ffile_list
In order to save the output in a file rather than standard output, use -o, --output, -a, --append to indicate the output file name, for instance:
pgn-extract -oall.pgn file1.pgn file2.pgn file3.pgn pgn-extract --output all.pgn file1.pgn file2.pgn file3.pgn
While pgn-extract can be used simply to check and reformat all the input games, it is more usual to use it to select subsets of the input games. Several different criteria are available on which to extract: move variations, information in the tag fields, and material balance in the ending, for instance. All of these criteria are described in detail below.
In order to output all matched games to a single new file, the -o flag is used:
pgn-extract -onew.pgn file1.pgn file2.pgn
This has the effect of creating new.pgn from the contents of file1.pgn and file2.pgn. The games in both source files are checked and rewritten, if necessary, into SAN. Any previous contents of new.pgn will be lost with the -o flag. In order to avoid this and append to an existing file, use the -a flag:
pgn-extract -anew.pgn file1.pgn file2.pgn
Note that there must be no space between either -o or -a and the output file name.
The long-form --output and --append are provided as alternatives to -o and -a, respectively. In these cases, there must be a space between the flag and the output filename. For instance:
pgn-extract --output new.pgn file1.pgn file2.pgn pgn-extract --append new.pgn file1.pgn file2.pgn
Check the input files for errors but do not output any matched games. Useful for cleaning up files of games before proper processing.
pgn-extract -r file.pgn
Useful with -s (silent mode) for checking a big file of games without having progress reported and just seeing the errors.
Error messages and verbose reporting is done to the standard error output unless the -l or -L flag is used. Both are immediately followed by the name of a file to which a log should be written. The -l flag creates a new log file, while -L appends to an existing log file:
pgn-extract -llog.txt file.pgn pgn-extract -Llog.txt file.pgn
This option is useful in combination with -r (report) to generate diagnostic information without outputting games while game data is being checked and cleaned.
A log file will contain only error reports if the -s (silent) flag is used.
There are two distinct ways to specify variations of interest; positional variations (the the -x flag) and textual variations (the -v flag). The major difference between the two is that positional variations specify a complete move sequence whose end position is the primary point of interest, whereas textual variations allow incomplete and fuzzy move sequence matches on the text of a game to select games. Whilst it is possible to use both flags together, this would be unusual as a game must match with both to be extracted.
Positional Variations (-x)
The variations in which you are interested should be placed in a file whose name is supplied with the -x flag. For instance:
pgn-extract -xvars
where each variation is listed on a single line in the file vars (the filename is immaterial). The following set of moves:
e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6
indicates that you wish to pick up all games reaching the Najdorf variation position of the Sicilian Defence. Games reaching the end position of this sequence are selected regardless of the route that was taken to reach it. This allows various transpositional sequences to be specified by quoting just one line to reach the required point. Therefore, games employing the following move order will be picked up by quoting the line above.
e4 c5 Nc3 d6 Nge2 Nf6 d4 cxd4 Nxd4 a6
A position is considered to match a required variation if it generates the same board hash value. In the interests of reasonable efficiency, no attempt is made to actually examine the state of the board. There is, therefore, the potential for false hits but in my usage of pgn-extract I have not found this to be a problem.
With this option, games are only searched to a depth approximately equal to the length of the longest positional variation, in order to make processing of large data sets faster than with a search of the whole game.
A comment line may be placed in a variation file by using a '%' as the first character of the line. Move numbers are optional within the list of moves.
Positional matches are also available using a FEN description of the desired position. See the description of the -t flag for how to specify a FEN position, and the -F flag for a simple way to generate a FEN description from a game score.
Textual Variations (-v)
With this option, the matching is purely textual in nature, in contrast to the -x flag. The -v flag works by string matching on the input text of moves, so there is no facility for picking up transpositions automatically. The variations in which you are interested should be placed in a file whose name is supplied with the -v flag. For instance:
pgn-extract -vvars
Each variation should be listed on a single line in the file vars (the filename is immaterial). The move sequence:
e4 c5 Nf3 d6 d4 cxd4 Nxd4 Nf6 Nc3 a6
indicates that you wish to pick up all games following the normal move order of the Najdorf variation of the Sicilian Defence, and
d4 Nf6 c4 e6 Nc3 Bb4
that you are interested in Nimzo-Indian games. The order in which the moves are played by either White or Black is immaterial. All combinations are tried, so the ordering:
c4 e6 Nc3 Bb4 d4 Nf6
will produce the same set of matches as the previous ordering of the Nimzo-Indian moves (see the -P flag for how to prevent this).
A comment line may be placed in a variation file by using a '%' as the first character of the line. Move numbers are optional within the list of moves.
As transpositions are not picked up automatically with this flag, if you also wanted to recognise the following as a Najdorf, you would have to add this line to the variations file in addition to that given above:
e4 c5 Nc3 d6 Nge2 Nf6 d4 cxd4 Nxd4 a6
However, because of the way in which the matching is done, it is possible to specify slight alternatives on the way in which individual moves are written. Notational alternatives for a single move are just written separated from each other with a non-move character. This variation specifies both the shorter and longer ways of writing the captures in a Najdorf:
e4 c5 Nf3 d6 d4 cxd4|cd Nxd4|Nd4 Nf6 Nc3 a6
However, given the variety of possible ways of writing various moves in non-SAN format, e.g.
cxd4|cd|c5d4|c5-d4
variation lists can get quite messy and I believe that this approach is best avoided by ensuring that the input is proper SAN and only using SAN notation in the variations file. In this way, the alternative-separator can then be used purely for indicating genuine alternative moves at that point, e.g.
e4 c5 Nf3 d6 d4|d3
An important point when listing moves is that check and mate indicators should be included where appropriate, otherwise moves incorporating these characters in games to be searched will fail to match.
There is little point in using the -v flag in preference to the -x flag if you are only interested in finding games that reach a particular position. The real use for -v is when you wish to pick up games in a more general way. For instance, the character '*' may be used in place of any move to indicate that you don't care what was played at that point. So the following:
* b6
means that you are interested in all games in which Black replied 1 ... b6 regardless of White's first move. The sequence:
d4 * c4 * Nc3 *
will pick up Nimzo-Indian, Grunfeld, King's Indian, etc. defences. This notation is not possible with positional variations.
In addition, the character '!' may be used in front of any move to indicate that you wish to disallow particular moves from matching at this point. For instance, if you want to find Sicilian games where White did not reply with Nf3 at move 2 you would specify:
e4 c5 !Nf3
If you wished to disallow 2.Ne2 as well then
e4 c5 !Nf3|Ne2
does the job. (Adding parentheses makes no difference as the '!' is applied to all of the following move string.)
Care should be taken combining '!', '*' and variation permutations (see the -P flag). Disallowed moves take precedence over '*' moves. If a single disallowed move is found in a game within the length of the variation, that game is excluded. This was the most sensible interpretation that I could find to place on this usage.
Textual Variation Permutations (-P)
Normally, all permutations of a textual variation (see the -v flag) are tried against the moves of a game. This cuts down on the number of separate transpositional orderings that it is necessary to list, at the cost of slower matching of each game. If the following were used to look for Nimzo-Indian games:
d4 Nf6 c4 e6 Nf6 Nc3 Bb4
a side-effect would be that it will also pick up games which start as:
1. c4 Nf6 2. Nc3 e6 3. d4 Bb4
for instance. The -P flag requests that textual variations are matched against the moves of the game strictly in the order in which they are listed, without trying different orders. So, if you want to find only those games that follow a particular move order, use this flag to suppress permutations.
If either the -d, --duplicates or -D flag is used, pgn-extract attempts to recognise duplicate extracted games. Using the -d or --duplicates flag indicates that you wish copies of the duplicate games to be written to the indicated file:
pgn-extract -ddupes.pgn -ounique.pgn file.pgn pgn-extract --duplicates dupes.pgn --output unique.pgn file.pgn
will both extract from file.pgn the unique set of games into unique.pgn and
the duplicates (i.e., the second and subsequent copies of a game)
to dupes.pgn.
A comment identifying in which file a
duplicate was found precedes the first duplicate found in that file and
each duplicate game has a prefix comment indicating the file in which
the first version was found.
Note that there must be no space between -d
and the filename
but a space between if --duplicates
is used.
With the -D flag duplicate games are suppressed from the output. These two flags are mutually exclusive, therefore.
Duplicates are identified by comparing a hash value for the board of the end positions of extracted games and an additional cumulative hash value generated from the move sequence. If these both values match then games are considered to be duplicates. This is not guaranteed to be exact but it gives a good approximation. If the position is important but the move sequence is not then use --fuzzydepth.
You should note that games are only considered to be duplicates on the basis of the moves played. It may be that a game considered to be a duplicate contains annotations and variations not present in the one found earlier, so it might be necessary to do some swapping around to obtain those you really wish to retain. You should, therefore, use the -D flag with caution if you are trying to reorganise your master collection rather than selecting out specific games for examination. (See also the -U flag.)
Detecting duplicates requires memory for the storage of a hash table containing information on each game. Large databases can result in a MallocOrDie error. If this is the case, try using the -Z flag which forces pgn-extract to store its hash table externally, in a file called virtual.tmp. Each game requires 16 bytes of file space. Clearly, if a very large database is being processed, there is a risk of filling up the available file space if there is insufficient available.
This flag allows a match on the basis of board position at the indicated number of plies or the end of the game. The flag is followed by the ply depth at which matches are to be considered. The value 0 is used to request matching at the end of games. It should always be used in combination with at least one of: -d/--duplicates, -D/--noduplicates, -U.
In contrast to the --duplicates matching, the match does not consider the move sequence used to reach the match position.
For example:
pgn-extract --fuzzydepth 40 -D games.pgn
would suppress from the output multiple copies of games reaching identical positions after 40 ply.
The following example would suppress the unique games and store the games considered to be duplicate at their final position in dupes.pgn:
pgn-extract --fuzzydepth 0 -U -ddupes.pgn games.pgn
The -U flag suppresses output of the first occurrence of a particular game. This is useful when combined with the -d flag as a means of identifying just those games that are duplicated in a list of multiple files. As the duplicate games are commented with the file in which they were located, it then becomes possible to prune a set of files containing common games. For instance, suppose oldfile.pgn contains a set of games without duplicates, and you wish to know which games in newfile.pgn already occur in oldfile.pgn:
pgn-extract -U -ddupes.pgn oldfile.pgn newfile.pgn
will write to dupes.pgn the duplicate games so that you can go through newfile.pgn and remove them. Of course, if you simply want to hold the combined set of unique games in a single file you would use something like:
pgn-extract -D -onewset.pgn oldfile.pgn newfile.pgn
See Duplicate Games for dealing with MallocOrDie errors.
Check files contain games that are to be used in duplicate detection, but not to form part of the output. If the filename appended to the argument has a .pgn/.PGN suffix it is assumed to be a single file of games. If it does not have this suffix then it is assumed to be a file containing a list of the names of PGN game files, one per line, to be used as check files.
A typical use for this is to select new games of interest from a file that probably contains games that exist elsewhere. In the following example, we wish to select Nimzo-Indian games from newfile.pgn that don't already occur in the master file nimzo.pgn:
pgn-extract -cnimzo.pgn -vnimzo.var -D -onewnimzo.pgn newfile.pgn
The games in nimzo.pgn act as the source for duplicate detection so duplicates of these will be suppressed (the -D flag). Only those games from newfile.pgn that are not in nimzo.pgn will be output to newnimzo.pgn. Contrast this behaviour with the following, which would create a new master file of games from the combination of nimzo.pgn and newfile.pgn:
pgn-extract -vnimzo.var -D -onewnimzo.pgn nimzo.pgn newfile.pgn
--checkfile is available as an alternative to -c and must be followed by a space before the filename, e.g.:
pgn-extract --checkfile nimzo.pgn -vnimzo.var -D -onewnimzo.pgn newfile.pgn
There are two ways to specify that you wish to use information in the tag fields as extraction criteria: the -t flag and the -T flag. The -t flag takes a file name argument and is the preferred method because of its ease of use and greater flexibility:
pgn-extract -ttags games.pgn
where tags is an arbitrary file name. In the file are listed tag name and value pairs corresponding to the extraction criteria you wish to use. Each line of this file should be of the form:
PGN-Tag-name Tag-stringfor instance:
White "Tal"
(note the need to include double quotes around the tag value). This requests that only those games where Tal had the White pieces are to be considered for extraction. If you wish to limit the year in which those games were played you might list:
White "Tal" Date "1962"
Multiple pairs with the same tag name are or-ed together so:
% Find games in the period 1960-1962. Date "1960" Date "1961" Date "1962"
will select all games from the three listed years. Note that comments may be included in the tag file.
In general, tags names that differ are and-ed together, so:
White "Tal" Black "Fischer" Date "1962" Result "1-0"
selects only those games that Tal won with the White pieces against Fischer in 1962.
It is important to note that:
White "Tal" Black "Tal"
does not find all games played by Tal, but only those that he played against himself. In order to overcome this, I have introduced a non-PGN tag that should only be used in the extraction criteria file:
Player "Tal" Date "1962"
finds all games from 1962 in which Tal had either the White pieces or the Black. In effect, the White and Black player lists are or-ed together rather than and-ed using this pseudo-tag.
Prefix matching on tag values is done so that a criterion should be a prefix of the complete Tag string. Thus,
Player "Karpov"
would match:
[White "Karpov"] [White "Karpov, A"] [White "Karpov, An"] [White "Karpov, Alexander"]
but not
[White "Anatoli Karpov"]
See the -S flag for a soundex facility with tag matching.
All tag criteria except ECO classification are checked before the moves of the game in the interests of efficiency (tag checking is relatively fast whereas positional checking of the game is not). Only once the game has been processed is it checked to see whether an ECO tag match has been requested. The consequence of this is that using the -e flag in combination with ECO tag criteria you can search for games in particular ECO lines without an ECO tag having been present in the input form.
FEN positional matches with -t
Use of a FEN tag with the -t flag has a special meaning. Rather than using this to match FEN tags in the header of a game, a FEN description is used to indicate a search for a positional match (similar to use of the -x flag). If a FEN description is provided with the -t flag, the indicated position is searched for in each game processed, and only those games that reach the indicated position are output. A FEN tag-pair for the starting position would be described by:
FEN "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
The position after the two moves e4 c5 would be:
FEN "rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2"
See details of the -F flag for a simple way to generate a FEN description from a game score.
There is a variation on use of a FEN with -t flag. The pseudo tag FENPattern takes a FEN-like description of a board containing meta characters that allow a fuzzy board match. In addition to the standard FEN characters having their usual meaning (1, 2, ... 8, R, N, B, etc.), the following meta characters are used:
Ranks within the pattern are separated with a '/' character, as usual, but there should be no characters other than the board position.
For instance:
FENPattern "rnbqkbnr/*/*/*/*/*/*/RNBQKBNR"
would match any board in which at least every non-pawn piece is on its starting square.
FENPattern "?????rk?/?????aaa/*/*/*/8/P[BP]P*/??KR????"
would match a board in which Black has a Kingside castled position behind three Black pieces (not necessarily pawns), White has a Queenside castled position with either a White pawn or bishop on b2 and the third rank is empty.
Date and Elo Matches with -t
From a -t tag file, more complex matching of dates and Elo values may be performed by placing an operator between the tag name and the tag string to be matched:
Date < "1962"
would only match games played before 1962. Only the year value participates in the matching process, as this is done using integer values rather than strings.
WhiteElo >= "2500"
only matches games where White is a strong player. Probably of more general use is another pseudo-tag that I have introduced purely for this purpose: Elo.
Elo >= "2500"
matches games in which either player has an Elo tag matching that relationship. The operators allowed are >, >=, <, <=, =, and <> (not equal to).
An alternative to the -t flag is the -T flag, for use where command line arguments are more convenient - perhaps where pgn-extract is being invoked from another program. The tag coverage is not as extensive as with a tag file, and the syntax is rather cumbersome. It is used as follows: after the -T comes a single letter from the limited set [abdeprw] to select string prefixes of the tag fields of a game. For instance:
For example,
pgn-extract -TwTal -TbFischer file.pgn
would extract games from file.pgn in which Tal had the White pieces and Fischer the Black.
Criteria of the same tag type are or-ed together, so
pgn-extract -Tr1-0 -Tr0-1 file.pgn
extracts only decisive games.
Criteria of different tag types are and-ed together so
pgn-extract -TwTal -Td1962 -Tr1-0 file.pgn
would extract only those games in which Tal played with the White pieces in 1962 and won.
The ECO classification (see the -e flag) is performed before attempting to match an ECO tag, so:
pgn-extract -TeA01 -e file.pgn
will perform ECO classification on the input file and extract games with ECO classification A01 (Nimzo-Larsen attack), for instance.
Date Matches with -T
A simple form of relational date matching is available. A date year may be prefixed with either 'b' or 'a' in order to match games played either before or after the specified date. This assumes that the date is stored in the game's date tag string in the normal form: YYYY.MM.DD
So,
pgn-extract -Tdb1962 file.pgn
will look for games played before 1962. A much fuller capability is available in tag files with the -t flag.
It can be inconvenient to repeatedly type long argument lists on the command line. The -A flag makes it possible to list arguments in a file, rather than on a command line. Each argument line within the file must be immediately preceded by a ':' (colon) character. Consider selecting games by Tal from a file caro.pgn and writing them to talgames.pgn. Using command line arguments, this would have the following form:
pgn-extract -TpTal -otalgames.pgn caro.pgn
We can do the same job placing the argument list in the file args:
% Select games by Tal. :-TpTal % Where to output the matched games. :-otalgames.pgn
and the same selection made with:
pgn-extract -Aargs caro.pgn
Note that comments may be included using a '%' character.
Each argument should be listed on its own line, and all the arguments are available in this way. The PGN source files may also be listed in the argument file. They must be listed one per line, with a preceding colon character. So an alternative for the above would be:
% Select games by Tal. :-TpTal % Where to output the matched games. :-otalgames.pgn % The game files to be read. :caro.pgn
and the command invoked as simply:
pgn-extract -Aargs
The -t, -v, -x, -z, and -R flags have slightly special treatment in an argument file. Where the tags, variations, positions, endings and/or roster ordering are to be read from files of those names, say, then the format of these arguments in the argument file might be as you would expect:
:-ttags :-vvariations :-xpositions :-zendings :-Rroster
However, within an argument file, the file names are optional and, where omitted, the data that would have been stored in a file for these flags is listed on lines immediately following. For instance, an alternative to:
:-TpTal
we could say:
:-t Player "Tal"
Notice that no colon should be present on the lines following the flag line. In the following example, we select games won by Tal as White reaching a particular position in the Caro Kann:
:-t White "Tal" Result "1-0" :-otalwins.pgn :-x e4 c6 d4 d5 exd5 cxd5 % Which game files to process. :caro.pgn
The arguments file may, itself, also contain -A arguments. This should make it possible to build up hierarchies of game selection criteria if desired. However, beware that there is no check for circularities in the dependencies.
The -n flag will cause all valid games not output via other criteria to be saved in a given file. The purpose of this is to make it easier to reorganise files in different ways. For instance, if you wish to remove all of the games played by Tal from one file, you might do:
pgn-extract -TpTal -otalgames.pgn -nothers.pgn file.pgn
After which, the file others.pgn will contain all of the valid games from the original file, with the exception of Tal's.
The tags for a game will not be output.
If comments (-C or --nocomments), NAGs (-N or --nonags) and/or variations (-V or --novars) are not required in the output then these can be suppressed by using one or more of these flags.
Move numbers can be suppressed from the output with --nomovenumbers. Used in combination with --notags, --noresults, -C, -N, and -V this can be used to output just the moves of a game:
pgn-extract --nomovenumbers --noresults --notags -C -N -V file.pgn
If it is desired to have all the moves on a single line, use the -w flag as well.
See also the --plylimit flag.
Results at the ends of games and variations can be suppressed from the output with --noresults. See suppressing move numbers for a possible use.
The number of moves (actually plies) output for a game can be limited by using --plylimit. This must be followed by the maximum number of plies to be output for a game. For instance,
pgn-extract --plylimit 10 --nomovenumbers --notags file.pgn
will output games up to a maximum of 10 plies (including variation lines), without game tags and no line numbers.
Note: If the game has not ended before the ply limit is reached then * will be used as the terminating result to indicate an incomplete game (see --noresults for how to suppress this.)
The -b flag allows you to select games which have a number of moves within the bounds you set. You can set a lower bound on the number of moves by using -bl ('l' = lower bound), or an upper limit by using -bu ('u' = upper bound). Both are followed by the number of moves so
pgn-extract -bu20 file.pgn
will find brevities of 20 moves or less, whilst
pgn-extract -bl60 file.pgn
will find games of 60 moves or move. Bounds may be combined so
pgn-extract -bl30 -bu40 file.pgn
will find games in the range [30..40] moves. If neither 'l' nor 'u' is used, but just a number following the -b, this means that the number of moves must exactly match that number. Alternatively, 'e' can be used to stand for 'equal to'. The following are equivalent and find all games of exactly 35 moves.
pgn-extract -b35 file.pgn pgn-extract -be35 file.pgn
The -M flag requests that only games that end in checkmate are matched:
pgn-extract -M file.pgn
The --stalemate flag requests that only games that end in stalemate are matched:
pgn-extract --stalemate file.pgn
The --underpromotion flag requests that only games that contain an underpromotion are matched:
pgn-extract --underpromotion file.pgn
A PGN file of ECO classifications is distributed with this version. I believe that this was put together by Ewart Shaw, Franz Hemmer and others, to whom appropriate thanks is due. The -e flag requests pgn-extract to add/replace ECO classifications in the games it outputs. This is done by firstly reading a file of ECO lines in PGN format (eco.pgn in the current directory, by default) and building a table of resulting positions. As the games are then read they are looked up in the table to find a classification. The deepest match is found. A match is allowed within six half moves of the length of the ECO line. The supplied file has ECO, Opening, and Variation tag strings for many lines. If present, pgn-extract will add/replace these as well as SubVariation tags if available.
An alternative file to the default eco.pgn may be supplied in two ways:
Appending a file name to the -e flag
-emy_eco_codes.pgn
Note that there must not be a space between the -e and the name of the file, otherwise the default ECO file will be assumed.
By setting the environment variable ECO_FILE to the full path name of the file. Under Windows this can be done with
set ECO_FILE=full-eco-file-path
at the Cmd window prompt, or more permanently via the System/Environment/Advanced area. Under UNIX csh this can be done with
setenv ECO_FILE full-eco-file-path
in the .cshrc, for instance.
Having the ECO data read as plain text on program startup has the obvious disadvantage that there is a high initial time overhead. On the other hand, it has the advantage that users may add their own classifications to the file very easily. It is fairly demanding of memory, so you advised not to combine this with duplicate detection (-U, -D and -d), which can also consume a lot of memory with big databases.
Because an ECO tag match with either the -t flag or the -T flag is delayed until after ECO classification, this makes it relatively easy to select games with particular ECO codes even if they weren't present in the source form.
Usage of -e with the Seven Tag Roster flag (-7) results in the ECO tags (ECO, Opening, Variation, SubVariation) being included in the output games.
The -# and -E flags permit the output to be split into multiple files. However, be warned that where the input involves a lot of games, these flags might result in the creation of a large number of output files.
The -# flag takes an unsigned integer argument specifying the maximum number of games to output to a single file. Successive output files are numbered 1.pgn, 2.pgn, etc. Any existing contents of these files are always overwritten on each run of pgn-extract.
pgn-extract -#250 file.pgn
will check and split file.pgn into separate files of, at most, 250 games each.
pgn-extract -#1 file.pgn
will split file.pgn into separate files containing only a single game each.
The -E flag normally takes a numeric argument of value 1, 2, or 3. This is used to indicate the level of subdivision required based upon the ECO tag found in a game.
pgn-extract -E3 file.pgn
will fully subdivide file.pgn into separate files based on the full ECO code of each game, with names such as B03.pgn, A01.pgn, D45.pgn, etc. If a game does not contain an ECO tag, or the tag appears to be malformed, it will be written to a file called, noeco.pgn. All of these files are written to in append mode, so that existing contents are not lost. However, beware of using an input file whose name is the same as one that will be written to by this operation. This could lead to infinite operation.
Level 1 classification uses just the initial letter of the ECO classification to append to files A.pgn, B.pgn, etc. Level 2 uses the initial letter and first digit, producing A0.pgn, B3.pgn, etc.
In fact, values greater than 3 may be used to produce separation of even finer granularity if more than two digits have been used in the classification of a game.
There is a simple soundex algorithm available that attempts soundex matches on White, Black, Site, Event, and Annotator tags if the -S flag is used in combination with either the -t flag or the -T flag. The -S flag should precede all -t and -T arguments. It should be noted that the soundex matching does produce false matches.
The -w flag allows an approximate line length to be set for output. Normally games are output with lines up to a maximum of 75 characters. Use the -w flag if you want longer output lines. For instance, you might want all the moves of a game to appear on a single line. You would get this effect by specifying -w1000 (say):
pgn-extract -w1000 file.pgn
If some games are more than 1000 characters long then just increase the value.
By default, pgn-extract rewrites the game score into English Standard Algebraic Notation (SAN) because it is reasonably flexible about the input form that it will accept. To prevent it from rewriting the original form of the moves it reads, use the -W flag.
Output using non-English piece letters is possible using a variation of the -Wsan flag. This flag may have a six-letter suffix indicating the letters to be used in representing pawn, knight, bishop, rook, queen and king in game scores and diagrams. So:
pgn-extract -WsanPNBRQK ...
would output in the (default) English notation, and
pgn-extract -WsanBSLTDK ...
would output in German. Note that the letter for a pawn is required because board positions are sometimes output when an error is detected in a game score.
-Wepd outputs in EPD (Extended Position Description). A game is output as a sequence of EPD descriptions of the position at the start of the game, and following each move. Each EPD line contains the FEN board description, the active colour, castling availability and en passant target square. A c0 comment contains a synopsis of the player, event, site and date tags from the game's header.
-Wuci outputs in long-algebraic notation (-Wlalg) but also strips the game of everything apart from its moves, tags and result. It provides the equivalent of using the following multiple arguments:
-Wlalg -C -N -V -w5000 --nomovenumbers --nochecksUse the --noresults and --notags options if tags and results are also to be removed.
-Wcm is an obsolete legacy flag and outputs the moves in what I believe to be (or used to be) ChessMaster format.
The -F flag provides a convenience method for generating a suitable FEN description of an arbitrary position. The -F flag causes pgn-extract to output a FEN description of the final position reached in a game, within the text of a comment. For instance, suppose you were interested in finding games that reach the position after the following moves.
d4 Nf6 c4 e6 Nf3 b6 Nc3 Bb7 e3 Bb4 Bd3 O-O O-O Bxc3 bxc3 c5 *
Storing these moves in the file fen.pgn and running
pgn-extract -F fen.pgn
would generate the score:
[Event "?"] [Site "?"] [Date "????.??.??"] [Round "?"] [White "?"] [Black "?"] [Result "*"] 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 Bb7 5. e3 Bb4 6. Bd3 O-O 7. O-O Bxc3 8. bxc3 c5 { "rn1q1rk1/pb1p1ppp/1p2pn2/2p5/2PP4/2PBPN2/P4PPP/R1BQ1RK1/ w - c6 0 9" } *
The -t flag makes it possible to use Forsyth-Edwards Notation (FEN) in the description of a position to be matched. For instance, the FEN string above could be cut and pasted to an argument file and used with the -t flag to supply matches:
:-t FEN "rn1q1rk1/pb1p1ppp/1p2pn2/2p5/2PP4/2PBPN2/P4PPP/R1BQ1RK1/ w - c6 0 9"
See --fencomments for the option to add a FEN comment after every move, including the final one.
The -z flag takes a filename of material balances for which you wish to search in games. The basic structure of the file is one or more lines of the form
pieces1 pieces2
Pieces1 and pieces2 are lists of English piece letters for the material for the two sides that you wish to look for in a game. For instance:
rp nb
looks for an game in which a lone Rook and Pawn for one side are competing against a lone Knight and Bishop for the other.
Text may be added after the piece lists as a form of comment.
A comment line may be placed in a material balance file by using a '%' as the first character of the line.
The --markmatches flag may be used to add a comment at the point that the match is found.
The case of the letters is immaterial, there is no need to include Kings in the description, and the order of the pieces does not matter. Apart from Kings, if a piece letter is not listed for a side then that piece is not present within that side's material. A match will be tested for from both White and Black's point of view, so the example above matches the same games as:
nb rp
Some notation may be added after any piece letter, typically to indicate something about the number of occurrences of that piece on one side.
The following are valid for each piece:
So:
QR2B2N2P8 QR2B2N2P8
is the starting material position, and QR+B*N*P7- represents material in which we require at least one pawn to be missing from one side and they should have a Queen and Rook, but we don't care about the minor pieces.
In addition, some extra notation is available to specify material relative to the opponent's. These are placed after the piece letter to which they refer.
So,
R+P+ R=P#
looks for Rook and Pawn games with an equal number of Rooks but unbalanced pawns.
In addition > and < may be preceded by a digit:
Two more notations, >=, <= may be preceded by an optional digit (the default is 1). The meaning of this may not be intuitively obvious and, to an extent, they represent a notational compromise.
In this example, both sides have a pair or Rooks but one has exactly one pawn more than the other:
r2p* r=p1>=
Here is an example where one side has sacrificed a Rook and Pawn for Knight and Bishop and we don't care whether Queens are on or off the board, so long as they are balanced:
q*r+n*b*p+ q=r<n>b>p1<
This example represents some of the imprecision that can occur with matches. The meaning of 'r<' is such that this could match positions in which one side as 2 Rooks and the other none. This can be corrected with:
q*r+n*b*p+ q=r1<=n>b>p1<
enforcing strictly one Rook less. We ought also to correct the same problem with the minor pieces:
q*r+n*b*p+ q=r1<=n1>=b1>=p1<
In practice, we probably want to allow general matching of minor pieces so the letter 'L' may be used to stand for a minor piece (Bishop or Knight). This example represents a similar sacrifice of Rook and Pawn for two minor pieces.
q*r+l*p+ q=r1<=l2>=p1<
I would advise against mixing the minor piece letter with Knight and Bishop letters in the piece set for a single side, however, as I am not convinced that it will produce exact results.
Position Stability with -z
The piece sets may be preceded by an optional number indicating the required stability of the position. Normally, if you are looking for a position with a particular set of material characteristics then you probably want that position to last for a reasonable number of moves in order to study its characteristics. The number before the piece sets is how many half-moves you wish that material balance to last. By default, this has a value of 2 so that fleeting positions in the middle of pairs of exchanges do not produce unwanted matches. This example looks for double-Rook and pawn games that last at least 10 half-moves:
10 R2P+ R=P*
This flag discards tag pairs that are not part of the Seven Tag Roster:
Event, Site, Date, Round, White, Black and Result.
However, if the original game included a FEN tag, this is included in the output, as the moves will make no sense otherwise. In addition, if the -e flag has been used for ECO classification, any ECO, Opening, Variation and SubVariation tags are also output.
The -R flag makes it possible for to define the order in which tags for a game are listed in the output. The flag should be immediately followed by the name of a file that contains a list of tag names, one per line, for instance:
pgn-extract -Rroster file.pgn
where roster might contain:
% Output the tags of the seven tag roster alphabetically. Black Date Event Result Round Site White
The '%' character may be used to include comments in the file. Tags not listed in such a file will appear after the required tags have been output.
The --evaluation argument causes a comment to be appended to every move, which contains an evaluation of the position immediately following that move. The default evaluation is a simplified version of Shannon's board evaluation. In this case, the evaluation is the difference between the value of White's position and Black's, where the value of a position is a weighted sum of the pieces plus a multiplier (0.1) applied to the number of available moves for that player.
I see this primarily as being a hook for people who wish to embed their
own evaluations in the output.
See the evaluate
function in apply.c
if you wish to
write your own.
The --fencomments argument causes a comment to be appended to every move, which contains a FEN string for the position immediately following that move. See -F for adding a comment after just the final move.
Add a game comment with the text immediately following --markmatches after the move which causes a positional or material match. For instance:
pgn-extract -xvars --markmatches MATCH file.pgn
would add the comment { MATCH } after every move that caused a match from the positional matches specified in the vars file.
See -x for positional matches with moves, -t for positional matches with FEN patterns, and -z for material matches.
I don't run a proper mailing list but if you find the program useful and would like or to offer suggestions that you think others might be interested in, then drop me a line at d.j.barnes@kent.ac.uk
The moves, variations, and commentary of each game are held internally and reformatted when a game is extracted, rather than reproducing the original text of the game source.
Lower-case 'b' as the first character of a move is taken to be a move of the b-pawn if one to match the move can be found. Otherwise, Bishop moves are tried as an alternative. There is no back-up on failure if picking a valid pawn move was the wrong choice.
Lower-case 'b' as the first character of a Bishop move is not acceptable in the variations files.
Duplicate detection is not guaranteed to be exact. The -Z flag has slightly more potential to avoid false duplicates as it compares separate values for the end position and move sequence, whereas these are XORed to save space when -Z is not used. However, this will only make a difference and avoid false matches if two different games at the same hashtable index also produce identical XORed values.
The results of the -x, -v, and -t/-T search criteria are AND-ed together. There might be occasions when you wanted to search for games that matched either positional variations or textual variations at the same time, for instance. This requires multiple runs of pgn-extract.
The -Wsan variation that allows selection of the output language is tied to single-character piece descriptions. This does not support Russian usage, for instance, in which the King is described as a character pair.
The sources include a Makefile for the GNU make program, gmake. I also use this with the Minimalist GNU for Windows compiler to produce a Windows command-line executable (see Portability).
The distribution comes with the following files.
COPYING | GNU General Public License |
Makefile | A build file suitable for use with the GNU make utility.
Windows users might like to use the mingw - Minimalist GNU for Windows version. |
apply.[ch] | functions concerned with applying moves to a board. |
argsfile.[ch] | functions concerned with command line argument processing. |
bool.h | Boolean type definition. |
decode.[ch] | functions for decoding the text of a move. |
defs.h | definitions relating to boards. |
eco.[ch] | functions for looking up ECO classifications. |
eco.pgn | PGN file of ECO classifications. |
end.[ch] | functions for looking for matching endgames. |
fenmatcher.[ch] | pattern matching for the FENPattern pseudo tag. |
grammar.[ch] | the parser. |
hashing.[ch] | duplicate detection hash tables. |
help.html | This file. |
lex.[ch] | the lexical analyser. |
lines.[ch] | functions for reading lines. |
lists.[ch] | functions for holding the extraction criteria. |
map.[ch] | functions for implementing move semantics. |
moves.[ch] | functions for collecting moves and variations. |
mymalloc.[ch] | functions for memory allocation. |
output.[ch] | functions concerned with outputting the games. |
taglist.h | constants for tag and pseudo-tag names |
tokens.h | type definition for lexical tokens. |
typedef.h | type definitions. |
pgn-extract is regularly used under Windows/DOS (using Minimalist GNU for Windows), and various versions of Linux and Mac OSX.
I would like to thank all those who used the program and made suggestions for things to add. In particular, thanks to Michael Kerry whose help led to better determination of game boundaries in earlier versions, and V. Armando Sole whose own filter program was the inspiration for adding textual variation permutations. John Brogan suggested adding the ! notation to the variation file and provided the spur for duplicate detection. He also supplied the original code for soundex matching (-S).
Jaroslav Poriz, Ron Leamon, Ed Leonard, Charles Frohman, and Robert Wilhelm helped with testing at various times. Bernhard Maerz was instrumental in encouraging the inclusion of ECO classification and material balance matches. He and Peter Otterstaetter suggested the relational operators in tag files, with Peter also providing the spur to make duplicate detection work with bigger game files (-Z) and doing some very useful testing for me.
Kayvan Sylvan requested long algebraic output and identified an error in ECO classification. Cameron Hayne suggested matching on the number of moves in a game. Owen D. Lyne suggested extension of the -E flag, and both tested and provided diagnostic data to help refine the ECO classification aspects of the program. Karl-Martin Skontorp provided the incentive and testing help that enabled me to add the -Wepd option.
Finally, thanks, of course, to Steven Edwards for his work on developing the PGN standard.
FEN pattern matching is based on pattern matching code by Rob Pike. Taken from: http://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html and ideas from Kernighan and Plauger's "Software Tools".
pgn-extract: a Portable Game Notation (PGN) extractor.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 1, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
David Barnes may be contacted as d.j.barnes@kent.ac.uk or via http://www.cs.kent.ac.uk/people/staff/djb/