LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Extracting the last section of a file (https://www.linuxquestions.org/questions/programming-9/extracting-the-last-section-of-a-file-864265/)

sylaan 02-22-2011 05:01 AM

Extracting the last section of a file
 
Hi all,

I have a file which looks something like this:

##########

some
text

text also includes empty lines

##########

some
more
text

##########



Basically all sections are separated by 10 hashes and I need to somehow only print all lines in the last section (the "some more text" part in the example above").

I tried all kind of things with sed and awk but I didn't find any way to identify the last "section".

Any help is appreciated.

Thanks,
Sylaan

z1p 02-22-2011 06:54 AM

This works for some versions of awk. Depends whether or not it supports multiple character record separators.
Code:

awk '{RS="##########";} END{print}'

grail 02-22-2011 07:25 AM

Actually, as the data ends with the separator the above will not work as the last entry is the empty data after the last separator.
Maybe try:
Code:

awk '/[^[:space:]]/{out = $0}END{print out}' RS="##########" file
This will save the last entry that contains something other than just white space

z1p 02-22-2011 04:15 PM

Quote:

Originally Posted by grail (Post 4267247)
Actually, as the data ends with the separator the above will not work as the last entry is the empty data after the last separator.
Maybe try:
Code:

awk '/[^[:space:]]/{out = $0}END{print out}' RS="##########" file
This will save the last entry that contains something other than just white space

Actually, the command I provided works if the '##########' is the absolute last thing in the file. If anything follows the '##########', even a newline, then you get that which may be blank.

So, yours is definitely more robust. Good one, thx for speaking up.

kurumi 02-22-2011 07:03 PM

Code:

$ ruby -0777 -lne 'print $_.split(/##+/)[-1]' file

sylaan 02-23-2011 06:54 AM

Quote:

Originally Posted by grail (Post 4267247)
Actually, as the data ends with the separator the above will not work as the last entry is the empty data after the last separator.
Maybe try:
Code:

awk '/[^[:space:]]/{out = $0}END{print out}' RS="##########" file
This will save the last entry that contains something other than just white space

Perfect, this worked! Initially it didn't but after testing it on another box, I realized I had some other kind of awk version installed. Installing GNU awk "fixed" it. Thank you :)


All times are GMT -5. The time now is 03:12 PM.