#!/usr/bin/perl # # This is an answer, in comments and code, to the question: # How to print data between tags from file sequentially? # URL: https://perlmonks.org/index.pl?node_id=1217156 # # LET'S EMBED THE FILE IN THE SCRIPT TO MAKE THIS EASY! # YOUR FILE IS NOW ANYTHING AFTER __DATA__ AT THE END: # # open file # open(FILE, "data.txt") or die("Unable to open file"); # # ALWAYS START WITH THESE TWO LINES, FOR HELPFUL ERROR MESSAGES: use strict; use warnings; # read file into an array # PUT my BEFORE ALL VARIABLES TO PREVENT TYPOS LATER ON: my @data = ; # close file # NOT NECESSARY ANYMORE: # close(FILE); # print file contents foreach my $line (@data) { # THIS PRINTS EACH LINE, NOT WHAT YOU WANT: # print $line; # MODIFY EACH LINE WITH A REGEX* FOR CUSTOM PRINT! # (*Short for "Regular Expression") # # Regex allows you to search and replace! # s is the command and // are the quotes: # s / FIND THIS TEXT / REPLACE WITH THIS / $line # For each line =~ # Do something like s/ # Search for < # a < character [^>]+ # and one or more characters: [ ]+ # that are not a > character: ^> > # Followed by a > character # (So anything like ) //gx; # Replace it with nothing: // # g means replace all of them (global) # x allows these comments because it is # usually put on one line like this: # # $line =~ s/<[^>]+>//g; # COOL! # NOW THE LINE IS CHANGED SO YOU CAN LOOK AT EACH LINE # WITH =~ TO FIND OUT WHICH TEXT TO PRINT: # SIMPLE: if ($line =~ /ServerName/) { print "Computer: $line"; } # SOMETHING MORE COMPLICATED: elsif ($line =~ /^ # IF LINE BEGINS WITH \d # A NUMBER (DIGIT) /x # (END REGEX, x JUST ALLOWS THESE COMMENTS) ){ # IF THE ELSIF DECISION IS YES BECAUSE WE # SAW A NUMBER, THEN DO THIS: print "IP Address: $line"; } # FIND WINDOWS OR LINUX OR MAC: # NOTE: i at the end of the next regex means # "case insensitive" so an "a" or "A" are equal. elsif ($line =~ /Windows|Linux|Mac/i) { print "OS: $line"; } # PRINT UNKNOWN LINES TOO SO YOU CAN SEE HOW # TO ADD MORE DECISIONS ABOVE AND MAKE IT # PRINT WHAT YOU WANT: else { print "UNKNOWN: $line"; } } # THE EMBEDDED FILE: __DATA__ ServerName 10.10.10.11 Windows Server 2012