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!

Search and print a field using pattern

Status
Not open for further replies.

indianya

Technical User
Aug 1, 2012
2
US
I have data file with null record separator and end of line as field separator. See below.

Date
pattern2
pattern3
pattern1

Date
pattern1
pattern2
pattern8

Date
pattern5
pattern6
pattern2

Date
pattern1
pattern2

I am only interested in field with pattern1. The problem is field number for pattern1 changes and in some records pattern1 doesn't exist.
I want to convert above data file so that only date and pattern1 is printed and if pattern1 is not found then date and 0 is printed. Desired output format is shown below.

Date,pattern1 (If pattern1 exists)
Date,0 (If pattern1 field doesn't exist)

Can someone throw some ideas on how to search and print only that field which matches pattern?
 
What have you tried so far and where in your code are you stuck

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
I have tried the following
nawk 'BEGIN { RS=""; FS="\n"; OFS=","}; /pattern1/ {print $1}' datafile

This prints date for records that have pattern1. But since pattern1 is in different field I don't know how to check for that. I think a for loop to check all the fields upto NF and then use of if to print the matching field would work but I don't know how to implement it
 
What about this ?
Code:
nawk 'BEGIN{RS="";FS="\n";OFS=","}{for(i=2;i<=NF;++i)if($i~/pattern1/){print $1,$i;next}print $1,0}' datafile

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top