0

I'm trying to read a specific section of a line out of a file with Perl. The file in question is of the following syntax.

# Sets $USER1$ 
$USER1$=/usr/....
# Sets $USER2$ 
#$USER2$=/usr/...

My oneliner is simple,

perl -ne 'm/^\$USER1\$\s*=\s*(\S*?)\s*$/m; print "$1";' /my/file

For some reason I'm getting the extraction for $1 repeated several times over, apparently once for every line in the file after my match occurs. What am I missing here?

Johannes Pille
  • 4,073
  • 4
  • 26
  • 27
Tim Brigham
  • 574
  • 1
  • 6
  • 24
  • You need a conditional to test for a match, such as `print if /..your regex ../;` –  Nov 30 '11 at 22:22

4 Answers4

5

You are executing print for every line of the file because print gets called for every line, whether the regex matches or not. Replace the first ; with an &&.

Jeff Burdges
  • 4,204
  • 23
  • 46
2

From perlre:

NOTE: Failed matches in Perl do not reset the match variables, which makes it easier to write code that tests for a series of more specific cases and remembers the best match.

Try this instead:

perl -ne 'print "$1" if m/^\$USER1\$\s*=\s*(\S*?)\s*$/m;' /my/file
ennuikiller
  • 46,381
  • 14
  • 112
  • 137
1
$ cat test.txt
# Sets $USER1$ 
$USER1$=/usr/....
# Sets $USER2$ 
#$USER2$=/usr/...

$ perl -nle 'print if /^\$USER1/;' test.txt
$USER1$=/usr/....
0

Try this

perl -ne '/^.*1?=([\w\W].*)$/;print "$1";' file
KKDK
  • 1