I want to say output lines 5 - 10 of a file, as arguments passed in.
How could I use head
and tail
to do this?
where firstline = $2
and lastline = $3
and filename = $1
.
Running it should look like this:
./lines.sh filename firstline lastline
try this one-liner:
in above line:
Aside from the answers given by fedorqui and Kent, you can also use a single
sed
command:Or, to avoid any external utilites, if you're using a recent version of bash (or zsh):
If you want lines from 20 to 30 that means you want 11 lines starting from 20 and finishing at 30:
That is, you firstly get first
30
lines and then you select the last11
(that is,30-20+1
).So in your code it would be:
Based on
firstline = $2
,lastline = $3
,filename = $1
Save this as "script.sh":
There is NO ERROR HANDLING (for simplicity) so you have to call your script as following:
./script.sh yourfile.txt firstline lastline
If you need only line "10" from yourfile.txt:
Please make sure that: (firstline > 0) AND (lastline > 0) AND (firstline <= lastline)