Re: Print word from text file that is not an exact match
by NetWallah (Canon) on Jun 09, 2018 at 04:07 UTC
|
You can use proper regex syntax to "capture" what you want :
if (my ($name) = $line=~/(Servername[\.\w]*)/){
print "$name\n";
}
Memory fault -- brain fried
| [reply] [d/l] |
|
|
Hi NetWallah,
Thanks so much for your quick response and a solution that works!
If you can please take a look at the following code and let me know what I am doing wrong I would greatly appreciate it.
If I can get this to work then I will be able to accomplish what I need to do for my first perl script. I think I am close to getting this to worK?
Thanks,
my $file = "computers.txt";
print "-->>Paste computer name(s) here, press enter key, then ctrl-D k
+eys<<--\n";
@computers = (<STDIN>);
foreach (@computers) {
open FILE, "$file";
while ($line=<FILE>){
if (my ($name) = $line=~/(@computers[\.\w]*)/){
print "name\n";
else
print "no match found\n";
close FILE, "$file";
}
}
}
Regards,
Tony
| [reply] [d/l] |
|
|
| [reply] |
|
|
|
|
|
Re: Print word from text file that is not an exact match
by Veltro (Hermit) on Jun 09, 2018 at 09:18 UTC
|
| [reply] |
|
|
Hi Veltro,
Thanks so much for the links. I will definitely check them out while I continue to learn from my O'Reilly Learning Perl book.
Regards,
Tony
| [reply] |
Re: Print word from text file that is not an exact match
by Laurent_R (Canon) on Jun 09, 2018 at 16:07 UTC
|
Regex capture is certainly the first option that comes to mind.
However, depending on how your data file is structured (BTW, it would be very useful to provide a data sample), you might also want to have a look at the split function.
| [reply] |
|
|
Hi Laurent,
The text file is a dump of a query and looks something like this:
<Answer type="string">ServerName1.org</Answer>
<Answer type="string">ServerName2.org</Answer>
<Answer type="string">ServerName3.org</Answer>
Regards,
Tony | [reply] [d/l] |
|
|
DB<1> $string = '<Answer type="string">ServerName.FD.net.org</Answer
+>';
DB<2> @fields = split /[<>]/, $string;
DB<3> x @fields; # displaying the content of the @fields array
+after the split
0 ''
1 'Answer type="string"'
2 'ServerName.FD.net.org'
3 '/Answer'
DB<4> print $fields[2]; # outputting the server name
ServerName.FD.net.org
You could also retrieve directly the server name without using a temporary array:
DB<1> $string = '<Answer type="string">ServerName.FD.net.org</Answer
+>';
DB<2> $name = (split /[<>]/, $string)[2];
DB<3> print $name;
ServerName.FD.net.org
But, again, a regex capture is simpler with your data format.
| [reply] [d/l] [select] |
|
|
|
|
|