Friday, May 21, 2010

Command line question unix/linux file commands?

If I have a file on linux/unix what would i type on the command line to display the midle line of of 3 lines of text.... in other words this is the question I am faced with here...





The file 'threelines' contains 3 lines of text. Display the middle line on


the screen. You are not allowed to use the more command.








any help will do??

Command line question unix/linux file commands?
head -2 threelines | tail -1 threelines








I'll break this statement down to explain it





head -2 threelines :this command displays the first two lines of the file


this output is sent as a input to the next command ( this is done by | (pipe))





tail -1 will display the last line of the output





so if your file is





abc


cde


fgh





head -2 gives





abc


cde





which is the input to tail -1





tail -1 taking this input will give only cde which the center line in your file





you can do it using awk also





cat newlines | awk 'NR==2 {print}'





in this you are printing out the lines in the file using cat,piping the output to the awk statement and saying select Number of record=2 and print it out (NR is number of record)
Reply:hey sorry made a mistake it should be head -2 threelines | tail -1





however the awk script should work fine.. Report It

Reply:That is a biggee of a question, my dear.
Reply:cat foo.txt | head -n 2 | tail -n 1





Something like that should do the trick.
Reply:Why don't you use grep for this, if more is not an option. You'll find evertything you need in the man pages.


No comments:

Post a Comment