INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Search and print a field using pattern

Search and print a field using pattern

(OP)
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?

RE: Search and print a field using pattern

(OP)
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

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close