1753912 Members
8573 Online
108810 Solutions
New Discussion юеВ

Re: Shell script.

 
SOLVED
Go to solution
LEJARRE Patrick
Advisor

Re: Shell script.

Hi Curt !
I read your script closely. I find it a little more complicated than the Andreas and Alan's scripts. I'm afraid your script would be more time and cpu consuming than the Andreas and Alan's ones.

Thank you very much for your contribution!
Pat.
curt larson
Frequent Advisor

Re: Shell script.

Well, my script is more complicated for a couple of reasons:

1) I extract only the line before the first occurance of the pattern as specified, not the line before every occurance of the pattern as alan's does

2) my script handles the situation if the pattern occurs in the first line. Alan's will output an empty line being prev will have no value at that time and will later remove all the blank lines from the file. I don't think this was your intention.

As far as time and cpu, my script would only do 3 greps and an awk on the file worst case (double that if you want to count creating the file of the deleted lines which could be removed if it isn't necessary), where if there is only 2 matches in the file alan's script will do 4 greps and an awk on the file. And with more matches alan's would do even more greps increasing by 2 greps for every line with a pattern match.

But, if you'd like to do it even faster:

#!/usr/bin/ksh

line_num=$(grep -n $pattern $mfile | awk -F: '{print $1;exit;}')

if [[ -n $line_num ]] ;then
if (( $line_num > 1 )) ;then

(( line_num = $line_num - 1 ))
sed -e '$line_num d'
-e '/$pattern/d' $mfile > $tmpfile

else
sed -e '/$pattern/d' $mfile > $tmpfile
fi
mv $tmpfile $mfile
fi

sorry, but I have a different opinion then you
nobody else has this problem
curt larson
Frequent Advisor

Re: Shell script.

and if you really want to spend the time maintaining an awk script:

#!/usr/bin/ksh


cat infile | awk '

BEGIN { First = "no";
Match = "no";
getline;
if ( $0 ~ /pattern/ ) {
First = "yes";
Match = "yes";
}
prev = $0;
}
{
if ( $0 ~ /pattern/ ) {
if ( First == "no" ) {
First = "yes";
}
else {
if ( Match == "no" ) {
print prev; }
}
Match = "yes";
}
else {
if ( Match == "no" ) {
print prev; }
Match = "no";
}
prev = $0
}
END
{ if ( Match == "no" ) print prev; }
' > outfile

mv outfile infile

myself the greps, seds, and eds are simplier to understand.
nobody else has this problem