I would like to print specific data after matching a pattern or line. I have a file like this:
#******************************
List : car
Design: S
Here's another option:
use strict;
use warnings;
print "Car Type\tNo.\n";
while (<>) {
if (/#-{32}/) {
print "$1\t$2\n" if <> =~ /(\S+)\s+(\S+)/;
<>;
}
}
Output:
Car Type No.
N17 bg099
A57 ft2233
L45 nh669
Usage: perl script.pl inFile [>outFile]
Edit: Simplified
I got your code to work with a couple small tweaks. It's still not perfect but it works.
Code:
$file_to_get = "input_file.txt";
open (FILE, $file_to_get) or die $!;
my @array;
while (@array = <FILE>) {
$i = 0;
foreach my $line (@array) {
if ($line =~ m/(Car)((.*))/) {
my $a = $array[$i+2];
push (@array, $a);
print $a;
}
$i++;
}
}
close(FILE);
a shell one-liner to do the same thing
echo "Car Type No. "; \
grep -A 2 Type data.txt \
| grep -v -E '(Type|-)' \
| grep -o -E '(\w+ *\w+)'
perl -lne 'if(/Type/){$a=<>;$a=<>;$a=~m/^([^\s]*)\s*([^\s]*)\s/g; print $1." ".$2}' your_file
tested:
> perl -lne 'if(/Type/){$a=<>;$a=<>;$a=~m/^([^\s]*)\s*([^\s]*)\s/g; print $1." ".$2}' temp
N17 bg099
A57 ft2233
L45 nh669
if you want to use awk,you can do this as below:
> awk '/Type/{getline;if($0~/^#---*/){getline;print $1,$2}}' your_file
N17 bg099
A57 ft2233
L45 nh669
Solution using Perl flip-flop operator. Assumption from the input that you always have Total line at the end of the block of interest
perl -ne '$a=/^#--/;$b=/^Total/;print if(($a .. $b) && !$a && !$b);' file
Something like this:
while (my $line = <>) {
next unless $line =~ /Car\s+Type/;
next unless $line = <> and $line =~ /^#----/;
next unless $line = <>;
my @fields = split ' ', $line;
print "@fields[0,1]\n";
}