I would like to search in a line for a string. After I found this string, I want to do a substr in that in order get ID. Here an example.
String Testname Testfile 21345 Anfragekennziffer 4519349 Teststring
4519349
.I wrote a script so far, that get me the Ids but only if "Anfragekennziffer" is at the beginning in a line. E.g:
line 1 "Anfragekennziffer4586268" result: "4586268"
line 2 "Anfragekennziffer5686797" result: "5686797"
E.G.
An input file could have the following content:
da adad Anfragekennziffer 6797456
dadad Anfragekennziffer6453914
dasdssss Anfragekennziffer6797433
dddsaaa Anfragekennziffer6609572
aaa Anfragekennziffer2435282
Anfragekennziffer 1234567
Anfragekennziffer21415666
My script (see below) would get the following result:
'nnziffer6','nziffer645','ennziffer6','nnziffer66','ffer243528','1234567','21415666'
So, I would like the script to start at "Anfragekennziffer" and get me the ID - npo matter where Anfragekennziffer is located in the line.
Here is my code so far:
#!/usr/bin/perl
use strict;
use warnings;
no warnings 'uninitialized';
my $Source = "Anfragekennziffer.txt";
my $SQL1 = "SQL_Confluence_Tabelle.txt";
my $SQL2 = "SQL_Provider_Antwort.txt";
my $time = localtime;
print "\n";
print "Local date and time: $time\n";
print "\n";
print "IDs wurden übertragen.\n";
print "Folgende SQL-Statements wurden erstellt:\n";
print "\n";
print "'SQL_Confluence_Tabelle'\n";
print "'SQL_Provider_Antwort'\n";
print "\n";
open(QUELLE, "$Source") or die "Open failed:$!";
open(ZIEL1, ">$SQL1") or die "Open failed:$!";
open(ZIEL2, ">$SQL2") or die "Open failed:$!";
my $ids;
my $weg;
while(my $row = <QUELLE>)
{
if ($row =~m/Anfragekennziffer/)
{
$row=substr($row,17,10); #gebe nur IDs aus
$row=~ s/^\s+|\s+$//g; #löscht Leerzeichen
$ids=$ids."'".$row."',"; #kumuliere IDs
$ids=~ s/\r|\n//g;
}
}
$weg=chop($ids);
print ZIEL1 "$ids";
print ZIEL2 "$ids";
close(QUELLE);
close(ZIEL1);
close(ZIEL2);
Would be great if someone would have an idea!
THANKS!
Finding the numbers after the keyword Anfragekennziffer
is easiest done using a regular expression that also matches the number and captures it:
my @ids;
while(my $row = <QUELLE>)
{
if ($row =~ m/Anfragekennziffer\s*(\d+)/)
{
push @ids, $1;
}
}
print join ",", @ids;
If you feel more comfortable using substr
, then the index function can give you the position where your keyword starts in the string and you can try to extract the number from there:
my @ids;
while(my $row = <QUELLE>)
{
if (my $pos = index('Anfragekennziffer', $row))
{
push @ids, substr( $row, $pos + length('Anfragekennziffer'), 10 );
}
}
print join ",", @ids;
This approach is far more fragile than the approach directly matching the number.
In both cases, instead of building a string, I've switched to accumulating the information in an array (@ids
) and then printing that array at the end using the join function. Keeping lists as arrays helps your code stay flexible in the case you want to do something else with the data later on.