Reputation: 89
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
Reputation: 5962
It appears that your input data is in CSV format. Here is a Perl solution based on Text::CSV
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
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 pattern1=[^,]\+
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) \+
by *
Upvotes: 1