%1, \1, and $1

Updated: 04/26/2017 by Computer Hope

%1, %1, and \1 variablesWhen used in a command line, script, or batch file, a %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can be used to print what is entered after the batch file name. In the example below of a batch file using the %1, the batch file will print "Hello xxxx it's nice to meet you", where xxxx is whatever you enter after the name of the batch file. So, if this batch file was named example.bat and you typed "example Nathan", the batch file would return "Hello Nathan it's nice to meet you".

@echo off
if "%1"=="" goto error
echo Hello %1 it's nice to meet you
goto end
echo type your name after batch file.

In other programming languages and script languages, the %1 may be substituted for \1 or $1. For example, in Perl, these could be used in a regular expression to print out the matched text or be used as a new variable. In the example below, if the $text variable contains any text, it will print "Hello xxxx", where xxxx is what is matched. So, if $text = "Joe Smith", the script would return "Hello Joe".

if ($text =~ s/^([a-z]+)/i) {
print "Hello $1\n";

Each of these matched strings or variables can also be extended upon by increasing the value. For example, the next matched string or variable found could be entered in as %2, \2, or $2. In the above batch file example, you could add a %2 to also print the last name as shown in the example below. If no last name was entered, the %2 would print nothing.

echo Hello %1 %2 it's nice to meet you

In the case of the above Perl example, adding $2 would print the second matched string within the parentheses, as shown below.

if ($text =~ s/^([a-z]+) ([a-z]+)/i) {
print "Hello $1 $2\n";

You can also add additional matched strings or variables by using 3, 4, 5, etc (e.g. %3, %4 or $3, $4)

$, Percent, Programming terms, Variable