head and tail command output together on file
Suppose I am having file named file1.txt
with the content as 1,2,3.. upto 100 linewise.
$> head -n 5 file1.txt //will display first 5 lines i.e. 1,2,3,4,5
$> tail -n 5 file1.txt // will display last 5 lines i.e. 96,97,98,99,100
I want to display the content as first 5 lines and last 5 lines together in 1 command,
$> head tail -n 5 file1.txt // Something like this 1,2,3,4,5 96,97,98,99,100 (both together)
how can I achieve this ?
You can use curly braces in bash to combine more than one command and having also their stdout and stderr combined:
{ head -n 5 file1.txt ; tail -n 5 file1.txt ; }
Notice that there is space character between the braces and the commands enclosed within them. That is because {
and }
are reserved words here (commands built into the shell). They mean group the outputs of all these commands together.
Also notice that the list of commands has to end with a semicolon (;
).
If you want to create an "alias" for such a command combination, you can create a function (a simple Bash alias will not work) in your .bash_aliases
file like this:
function headtail
{
head "$@" ; tail "$@"
}
And you can call this function like this, for example:
headtail -n6 file1.txt | wc -l
In the above example, if file1.txt
is has at least 6 lines, you will get an output of 12
from the wc
command.
Processing in a sub-shell:
(head -n 5; tail -n 5) < file1.txt