Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Required value occurs on next line to matched pattern

Status
Not open for further replies.
May 5, 2003
2
NZ
Hi there,
I'm trying to retrieve a value which occurs directly after a certain string "cost" in a text file. However it occurs in a different position in the line each time and occasionally the value needed is on the next line..
Any ideas much appreciated.
Thanks
Brett
 
How do you recognise the value when it's present in a line?

You could start with

# set a flag when we see a cost
flag == 0 && /cost/ { flag = 1; }
# seen cost, now look for value
flag == 1 && /something/ { something_else; flag = 0; }

The flag allows you to keep the state from one line to the next.

The next step is identifying the value once you've seen the cost.
 
This code will search the file for a line containing the string 'cost', then store each field on the line and the next line into an array which is then searched for 'cost' again to print the field after.

awk '/cost/ {
s=$0;
getline;
s=s $0;
split(s,a);
for (i in a) {
if (a=="cost") {
print a[i+1];
};
};
}' <file1
 
Another method is to use match and an interactive
search to afford yourself some flexibility.

Code:
BEGIN {

       printf &quot;Stringpat to search: &quot;
       getline str < &quot;-&quot;
       }
{

    if ($0 ~ /cost/ && (p = match($0,str)) > 0) {
       print substr($0,p,length($0) - p), &quot;at Line&quot;, NR
    } else if (p < 1) {
       getline
       if ( (p = match($0,str)) > 0) {
            print substr($0,p,length($0) - p),&quot;at Line &quot;, NR
       }
    }
}
 
Thanks very much everyone,
I need to research some more on this but i think i am over the initial hump now.
Thanks again
Brett
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top