user4786572
user4786572

Reputation: 89

How I search and print matched wold in UNIX or perl?

1=ABC,2=mnz,3=xyz
1=pqr,3=ijk,2=lmn

I have this in text file I want to search 1= and that should print only matched word 1=ABC and 1=pqr

Any suggestions in Perl or Unix?

Upvotes: 0

Views: 47

Answers (2)

Stefan Becker
Stefan Becker

Reputation: 5962

It appears that your input data is in CSV format. Here is a Perl solution based on Text::CSV

  • parse the CSV content row-wise
  • print out columns that start with 1=
#!/usr/bin/perl
use warnings;
use strict;

use Text::CSV;

my $csv = Text::CSV->new({
    binary   => 1,
    eol      => "\n",
}) or die "CSV\n";

# parse
while (my $row = $csv->getline(\*DATA)) {
    foreach (@{ $row }) {
        print "$_\n" if /^1=/;
    }
}

exit 0;

__DATA__
1=ABC,2=mnz,3=xyz
1=pqr,3=ijk,2=lmn

Test run:

$ perl dummy.pl
1=ABC
1=pqr

Replace DATA with STDIN to read the input from standard input instead.

Upvotes: 0

Allan
Allan

Reputation: 12438

Input:

$ cat grep.in 
1=ABC,2=mnz,3=xyz
1=pqr,3=ijk,2=lmn
4=pqr,3=ijk,2=lmn

Command:

$ grep -o '1=[^,]\+' grep.in 
1=ABC
1=pqr

Explanations:

You can just use grep on your input

  • -o is to output only the matching pattern
  • 1=[^,]\+ the regex will match strings that start by 1= followed by at least one character that is not a comma (I have based this on the hypothesis that there is no comma in the right part of the = except the separator)
  • if you want to accept empty result you can change the \+ by *

Upvotes: 1

Related Questions