%1, \1, and $1

Updated: 11/16/2019 by Computer Hope
%1, %1, and \1 variables

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.

In the example below, using the %1, the batch file prints "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 prints "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 Perl example above, adding $2 would print the second matched string in 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 with 3, 4, 5, etc. (E.g., %3, %4 or $3, $4.)

$, Percent, Programming terms, Variable