%1, \1, and $1

Updated: 12/31/2022 by Computer Hope
%1, %1, and \1 variables

When used in a command line, script, or batch file, %1 represents 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 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 matched strings or variable can also be extended by increasing the value. For example, the next matched string or variable found could be entered as %2, \2, or $2. In the above batch file example, you could add a %2 to print the last name, as shown below. If no last name were 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