Extract error records based on specific criteria from Unix file

Hi,

I look for a awk one liner for below issue.

input file

ABC 1234 abc 12345
ABC 4567 678 XYZ
xyz ght 678
ABC 787 yyuu
ABC 789 7890 777
zxr hyip hyu
mno uii 678 776
ABC ty7 888 

All lines should be started with ABC as first field. If a record has another value for 1st field, the previuos record with ABC also an error record. I need to get the output as below

ABC 4567 678 XYZ
xyz ght 678
ABC 789 7890 777
zxr hyip hyu
mno uii 678 776

i have written a code by using while ... do ... done. but for bigger files this takes lot of time as this code reads file record by record.
Please help.

Thanks
RAR.

I think your O/P and the explanation doesn't match :frowning:

i have written a code by using while ... do ... done

post your code.......

you can use this perl code

 
$ cat pp.pl
#!/usr/bin/perl -w
use strict;
chomp(my @arr=<>);
my $i=0;
for (@arr)
{
        if (!/^ABC/)
        {
                my $x=$i-1;
                print "Line ".$i.":".$arr[$x]."\n";
                print "Line ".($i+1).":".$_."\n";
        }
$i++;
}

while runing this code, club it with sort -u

 
$ ./pp.pl a.txt| sort -u

output

 
Line 2:ABC 4567 678 XYZ
Line 3:xyz ght 678
Line 5:ABC 789 7890 777
Line 6:zxr hyip hyu
Line 7:mno uii 678 776

My requirement is extract error records. Output shows error records.

My code is

cnt=1
cat input_file | while read line
do
typ=`echo "$line" | cut -c 1-3`
if [ $cnt -gt 1 ]
then
if [ typ != "ABC" ] || [ pre_typ != "ABC" ]
then
echo $pre_line >> output_file
fi
fi
cnt = 2
pre_typ=$typ
pre_line=$line
done
if [ typ != "ABC" ] || [ pre_typ != "ABC" ]
then
echo $pre_line >> output_file
fi
 

Please give me a better logic.

I don't understand what you mean by extract error records,
my code is giving the exact output you wanted (as mentioned in your post)
if you want the output in a file you can just direct the output towards one

$ ./pp.pl a.txt| sort -u > ErrorFile.txt
$awk '$1 ~ /ABC/{if(x ~/ABC/){print $0};x=$1}($1 !~ /ABC/){x=$1;print}'  inputfile

Thank a lot raj_saini20 for your code, it is working fine for my requirement, when I made a small change.

$awk '$1 ~ /ABC/{if(x !~/ABC/){print $0};x=$1}($1 !~ /ABC/){x=$1;print}'  inputfile

This gives the last row also, even if it is a valid record starting with ABC.
So I skipped the last record in my output file.

sam05121988,

Script gives me below output, not giving lines starting with ABC.

xyz ght 678
zxr hyip hyu
mno uii 678 776

Thanks you all for your valuable inputs.

RAR

---------- Post updated at 02:56 PM ---------- Previous update was at 02:53 PM ----------

:b: