Plutôt que d’utiliser des outils conçus pour traiter des fichiers texte, utilisez un parsingur HTML, tel que Mojo::DOM
pour Perl:
use ssortingct; use warnings; use feature ":5.10"; use Mojo::DOM; use List::Util "first"; # construct DOM object from file my $d = Mojo::DOM->new(do { local $/; <> }); # get all tags my $a = $d->find("a"); # find the index of the one we are interestd in my $href = 'https://stackoverflow.com/laptops/samsung~brand/pr?sid=6bo,b5g'; my $index = first { $a->[$_]->attr('href') eq $href } 0..$a->size; # print links say $a->slice($index-4..$index+4)->map("to_ssortingng")->join("\n");
Exécutez-le comme perl script.pl file.html
.
Sortie:
Camera Tripod View all Apple Laptop Acer Laptop Samsung Laptop Lenovo Laptop Sony Laptop Dell Laptop Asus Laptop
Voici quelques suggestions non testées
Pour passer des options au script, à la grep, vous pouvez utiliser Getopt::Std
:
use Getopt::Std; our($opt_A, $opt_B) = (0, 0); getopts('A:B:');
Cela vous permettrait de passer les options -A
et -B
au script, comme perl script.pl -A 4 -B 4 file.html
. Vous pourriez alors changer le 4
s codé en dur dans le code ci-dessus en ($index-$opt_A..$index+$opt_B)
.
Pour transmettre également le motif, vous pouvez spécifier une autre option.
Pour colorer le résultat sur la ligne qui vous intéresse, vous pouvez utiliser Term::ANSIColor
:
say $a->slice($index-4..$index-1)->map("to_ssortingng")->join("\n"); say green $a->[$index]->to_ssortingng; say $a->slice($index+1..$index+4)->map("to_ssortingng")->join("\n");
grep comme suit
grep --color -F -A 4 -B 4 'https://stackoverflow.com/laptops/samsung~brand/pr?sid=6bo,b5g' 'my_file'
MODIFIER
Puisque toutes les données se trouvent sur une ligne, vous pouvez utiliser grep pour trouver la chaîne et les caractères entourant la chaîne.
grep -o --color '.\{0,3\}https://stackoverflow.com/laptops/samsung~brand/pr?sid=6bo,b5g.\{0,3\}
Cela trouvera le motif et imprimera 3 caractères avant et après la chaîne
.
before et after la chaîne représente n’importe quel caractère sauf newline char.