Hi,
I have to search a word in a text file and then I have to delete lines above from the word searched . For eg suppose the file is like this:
Records
P1
10,23423432
,77:1
,234:2
P2
10,9089004
,77:1
,234:2
,87:123
,9898:2
P3
456456
P1
:123,456456546
P2
abc:324234
,89237494
P3
,98:234
.
.
.
and so on.
The file contains thousands of records.
Now I have to search for a particular word for eg I am searching 9089004. Then the records in which 9089004 will lie I mean from P1 till P3 will be deleted from the file and rest of the records will exist in the file. The problem is that the word can exist anywhere between P1 to P2 or from P2 to P3 and then I have to delete that record i.e. from P1 to P3.
Please help
See if this works for you:
#!/usr/bin/ksh
rm -f temp_file
rm -f out_file
mP1="N"
while read mLine; do
mTag=$(echo ${mLine} | cut -c1-2)
if [[ "${mTag}" = "P1" ]]; then
mP1="Y"
fi
if [[ "${mP1}" = "Y" ]]; then
echo ${mLine} >> temp_file
else
echo ${mLine} >> out_file
fi
if [[ "${mTag}" = "P3" ]]; then
mStr=$(egrep '9089004' temp_file)
if [[ "${mStr}" = "" ]]; then
cat temp_file >> out_file
fi
rm -f temp_file
mP1="N"
fi
done < inp_file
Thanks for your reply ...... shell_life .....
It is working fine , but I am getting P3 records above P1
For eg the input file is:
If I am searching the number 9881119347
P1
123
P2
9881119347,87
P3
9881119347
P1
998811347
P2
34534
P3
98811147
P1
78686
P2
902384930284
P3
2904898
Then the output generating is:
9881119347
P1
998811347
P2
34534
P3
98811147
P1
78686
P2
902384930284
P3
2904898
But it should be like below:
P1
998811347
P2
34534
P3
98811147
P1
78686
P2
902384930284
P3
2904898
I am searching only till P3..but I have to search before the next P1 occurs...Please check the output that is required.
Kindly advice