I have a file containing records e.g. file.dat below.
Now I want to extract the last line from each record and insert this
into a new file, filenew.dat
file.dat
1 3 5
2 4 6
1 6 9 #extract this
3 9 4
3 8 2
8 4 7
4 7 2 #extract this
8 4 1
3 6 2 #extract this
....EOF...
Could anybody please help me with tihis?
Is there a way to use grep in this problem?
For these kinds of problems you can't just use grep. You have to write some code. If you don't know awk, then use another language that you are familiar with.
Thanks Ygor.
When it comes to the first question (partly) I used ruby code (provided by futurelet on a previous question) to sort each record with respect to the z-value, resulting in the largest z-value at the bottom of each record.
Then I used the code given by you on the second question to extract the last line of each record and inserting this into a new file, producing a file with maximum z-values.
Hi Ygor!
Could you please explain the awk code for extracting last line in the record?
I tried to use the code on records containing only two fields, but then it only printed the last line from the last record. Why?
RS is awk's input record separator. Its default value is a string containing a single newline character, which means that an input record consists of a single line of text. (See How Input is Split into Records .)
The empty string, "" (a string of no characters), has a special meaning as the value of RS: it means that records are separated only by blank lines. See Multiple-Line Records, for more details.
NF is the number of fields in the current input record. NF is set each time a new record is read, when a new field is created, or when $0 changes (see Examining Fields).
The last field in a record is $NF, the second last is $(NF-1).