Say you have a txt file, what is the command to view the top 10 lines and bottom 10 lines of file simultaneously?
i.e. if the file is 200 lines long, then view lines
I have been looking for this solution for a while. Tried it myself with sed, but the problem with not knowing the length of file/stream beforehand was insurmountable. Of all the options available above, I like Camille Goudeseune's awk solution. He did make a note that his solution left extra blank lines in the output with a sufficiently small data set. Here I provide a modification of his solution that removes the extra lines.
headtail() { awk -v offset="$1" '{ if (NR <= offset) print; else { a[NR] = $0; delete a[NR-offset] } } END { a_count=0; for (i in a) {a_count++}; for (i=NR-a_count+1; i<=NR; i++) print a[i] }' ; }
sed -n "1,10p; $(( $(wc -l ${aFile} | grep -oE "^[[:digit:]]+")-9 )),\$p" "${aFile}"
NOTE: The aFile variable contains the file's full path.
ed
is the standard text editor
$ echo -e '1+10,$-10d\n%p' | ed -s file.txt
First 10 lines of file.ext, then its last 10 lines:
cat file.ext | head -10 && cat file.ext | tail -10
Last 10 lines of the file, then the first 10:
cat file.ext | tail -10 && cat file.ext | head -10
You can then pipe the output elsewhere too:
(cat file.ext | head -10 && cat file.ext | tail -10 ) | your_program
Well, you can always chain them together. Like so,
head fiename_foo && tail filename_foo
. If that is not sufficient, you could write yourself a bash function in your .profile file or any login file that you use:
head_and_tail() {
head $1 && tail $1
}
And, later invoke it from your shell prompt: head_and_tail filename_foo
.
drawing on ideas above (tested bash & zsh)
but using an alias 'hat' Head and Tails
alias hat='(head -5 && echo "^^^------vvv" && tail -5) < '
hat large.sql