LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   reading second last line from a file and save in variable (https://www.linuxquestions.org/questions/linux-newbie-8/reading-second-last-line-from-a-file-and-save-in-variable-4175516376/)

vjlxmi 08-26-2014 01:27 AM

reading second last line from a file and save in variable
 
I have a file say 'fileX' which consists of 'n' number of lines. I want to read just the second last line from the file and store it in a variable. Can someone plz help me with the code.
Thanks in advance.

jdkaye 08-26-2014 01:34 AM

Is this a homework assignment by any chance. Why not show us how far you've gone and what problems you are encountering. It will be easier to help you when we see what your problem is.
jdk

vjlxmi 08-26-2014 06:01 AM

I was thinkin abt checking the number of lines in the file using the 'wc -l' command and storing the value in a variable. And then (n-1)th value using 'sed' would hopefully go to the correct line and give me the required answer.
Is there any easier way to do it?

sycamorex 08-26-2014 06:14 AM

Can't you Google it? Just did it and there are lots of examples how to display last but one Line. Some ways involve sed only; some of them the combination of head and tail. There is no need to count the number of lines.

vjlxmi 08-26-2014 06:35 AM

I've Googled a lot.. and found many examples to display value at a specific line number. But in my case, the lines keep on increasing in the file and the line number is not known for the second last value.

syg00 08-26-2014 06:46 AM

As suggested, search "last but one", not "second last" - the google engine seems to handle the former better.

vjlxmi 08-26-2014 07:00 AM

tail -2 yourfile | head -1
works.. Thanks for the help. :)


All times are GMT -5. The time now is 09:35 AM.