Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a text file sample.txt as:

=====record1
title:javabook
price:$120
author:john
path:d:
=====record2
title:.netbook
author:paul
path:f:
=====record3
author:john
title:phpbook
subject:php
path:f:
price:$150
=====record4
title:phpbook
subject:php
path:f:
price:$150

From this I want to split the data based on author. It should split into two files which contain:

test1.txt

=====record1
    title:javabook
    price:$120
    author:john
    path:d:
=====record3
    author:john
    title:phpbook
    subject:php
    path:f:
    price:$150

and

test2.txt

=====record2
    title:.netbook
    author:paul
    path:f:

I want to dynamically classify the main sample.txt file into subfiles based on the author field.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Using awk, store the fields in variables. When the record marker is reached, write the fields into the appropriate file (using author's name).

-F: specifies the fields are delimited on ":"

This line $1 ~ /author/ { author=$2 } if the first field of a line is "author" then store the value in the author variable. This is required as there must be an author named file to write the record to.

Using substr() to extract the first five characters, if the beginning of record marker "=====" if found then the data (stored in the rec variable) is written to the appropriate author file.

 awk -F: '
    $1 ~ /author/ { author=$2; }
    {
        if (substr($1,0,5) == "=====" && author != "") {
            print rec >> (author".txt")
            rec=$0; author=""
        }
        else
            rec=rec "\n" $0
    }
    END { if (author != "") print rec >> (author".txt") }
    ' authors.txt
share|improve this answer
    
thanks its working can you explain me the code please? –  user2353439 Jun 4 '13 at 9:31
    
You are welcome - more explanation now added. –  suspectus Jun 4 '13 at 9:38
    
thanks, i have one more doubt,my text file consists of 10 records and each record has 15 to 20 fields and all the records does not have same number of fields.so, can i use same code to my text file also?please suggest me how to do it? –  user2353439 Jun 4 '13 at 9:47
    
and what is the use of this line "if (length(title) > 0)", why only title has been considered.... –  user2353439 Jun 4 '13 at 9:50
    
You will need to write some additional code to cope with the 15 to 20 fields. If the fields follow the same format then that should be a simple task. Why length(title) > 0? My reasoning was if a record had a title it must be a valid record. –  suspectus Jun 4 '13 at 9:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.