LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Shell scripting: print first line and last line only (https://www.linuxquestions.org/questions/programming-9/shell-scripting-print-first-line-and-last-line-only-554978/)

Micro420 05-18-2007 02:39 PM

Shell scripting: print first line and last line only
 
Is there a way to print the first line of a file and the last line of a file with one command?

For example:

1
2
3
4
5

and I only want it to be

1
5

Assume that I don't know how many lines are in between the first and last line. The only way I could think of was to do:

head -n 1 filename > tempfile
tail -n 1 filename >> tempfile

jim mcnamara 05-18-2007 03:25 PM

Code:

sed -n '1p;$p' filename > newfile

Micro420 05-20-2007 12:42 PM

That works great! now, how about something a little more trickier. What if the list looked like this and I wanted to print from "/program/" to the end

apple
oranges
789
/program/
1
2
3
4
5

Assume that my list is random, but I always want to start from "/program/" until the end.

And also, would there be a way to start and stop at a certain point? For example, start at "/program/" and stop at "3"

druuna 05-20-2007 01:59 PM

Hi,

You can use regular expression to express line numbers in sed. I.e:

'Normal':

sed -n '15,$p' infile
Would print line 15 (included) to end of file.

Using regexp:

sed -n'/\/program\//,$p' infile
Would print from the first found /program/ to end of file.

Hope this helps.

homey 05-20-2007 03:05 PM

In the case of searching from one regexp to another, you have a situation where the second regexp is a number.

Code:

If you use this...
sed -n '/\/program\//,3p' file.txt
sed is looking for a line number (3) which it already passed so,
you only get an output of
/program/

You get the desired result by putting both regexp inside / like this
Code:

sed -n '/\/program\//,/3/p' file.txt

ghostdog74 05-20-2007 06:26 PM

Quote:

Is there a way to print the first line of a file and the last line of a file with one command?
Code:

awk 'NR==1 {print}END{print }' file
Quote:

That works great! now, how about something a little more trickier. What if the list looked like this and I wanted to print from "/program/" to the end

apple
oranges
789
/program/
1
2
3
4
5

Assume that my list is random, but I always want to start from "/program/" until the end.
Code:

awk '/program/,$NR{print}' "file"
Quote:

And also, would there be a way to start and stop at a certain point? For example, start at "/program/" and stop at "3"
Code:

awk '/program/,/^3/{print}' "file"


All times are GMT -5. The time now is 07:09 PM.