Perl: How to print next line after matching a pattern?

后端 未结 7 1946
刺人心
刺人心 2021-01-06 15:52

I would like to print specific data after matching a pattern or line. I have a file like this:

#******************************    
List : car  
Design: S           


        
相关标签:
7条回答
  • 2021-01-06 15:53

    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

    0 讨论(0)
  • 2021-01-06 15:54

    I got your code to work with a couple small tweaks. It's still not perfect but it works.

    • "while" should be lower case.
    • You never increment $i.
    • The way you reuse @array is confusing at best, but if you just output $a you'll get your car data.

    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);
    
    0 讨论(0)
  • 2021-01-06 15:54

    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+)'
    
    0 讨论(0)
  • 2021-01-06 16:04
    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
    
    0 讨论(0)
  • 2021-01-06 16:09

    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
    
    0 讨论(0)
  • 2021-01-06 16:14

    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";
    }
    
    0 讨论(0)
提交回复
热议问题