Bash method for viewing beginning and end of fileCommand to display first few and last few lines of a fileRace Condition for Shell Blocks in Bash?Add character to beginning and end of columnHow to transform two delimited ASCII filesusing awk to create a LaTex table from my data in a text fileAppend columns in a text file to after the final rowRemove spaces and headers from a dumped database tableCount the maximum character length for all the data fields in a simplified csv file and output to txtWriting a program for editing .txt data - Python or Unix?Merging two Unix filesegrep regular expression - same word in the beginning and endhow to evaluate number between a range of numbers using different variables in bash

How does the UK government determine the size of a mandate?

What is the difference between "behavior" and "behaviour"?

Why Were Madagascar and New Zealand Discovered So Late?

Is there a problem with hiding "forgot password" until it's needed?

How can a function with a hole (removable discontinuity) equal a function with no hole?

Unexpected indention in bibliography items (beamer)

Fastening aluminum fascia to wooden subfascia

Is a stroke of luck acceptable after a series of unfavorable events?

Why are there no referendums in the US?

Is this apparent Class Action settlement a spam message?

How do scammers retract money, while you can’t?

Valid Badminton Score?

Term for the "extreme-extension" version of a straw man fallacy?

Closest Prime Number

Trouble understanding the speech of overseas colleagues

What does this 7 mean above the f flat

Is this version of a gravity generator feasible?

Does "every" first-order theory have a finitely axiomatizable conservative extension?

Increase performance creating Mandelbrot set in python

Italian words for tools

Pole-zeros of a real-valued causal FIR system

How to safely derail a train during transit?

What is paid subscription needed for in Mortal Kombat 11?

Did Dumbledore lie to Harry about how long he had James Potter's invisibility cloak when he was examining it? If so, why?



Bash method for viewing beginning and end of file


Command to display first few and last few lines of a fileRace Condition for Shell Blocks in Bash?Add character to beginning and end of columnHow to transform two delimited ASCII filesusing awk to create a LaTex table from my data in a text fileAppend columns in a text file to after the final rowRemove spaces and headers from a dumped database tableCount the maximum character length for all the data fields in a simplified csv file and output to txtWriting a program for editing .txt data - Python or Unix?Merging two Unix filesegrep regular expression - same word in the beginning and endhow to evaluate number between a range of numbers using different variables in bash













7















On queue-based clusters the Queue of pending jobs is shown from a command, say showqueue.



The command returns, in columns, a list of reasonable data like names, etc, but the columns/data don't really matter for the question.



I like using the utility watch like watch showqueue at times (with an alias of alias watch="watch " to force alias expansion of my command to watch). There is valuable data (Running jobs), in the first few lines, then pending jobs, etc, and some valuable summaries at the end.



However, at times the output of showqueue goes off the screen (Unbelievable, I know)! Ideally, I'd like some way to be able to see the beginning and end of the file at the same time.



The best I have so far is: showqueue > file; head -n 20 file > file2; echo "..." >> file2 ; tail -n 20 file >> file2; cat file2, and using watch on an alias of that.



Does anyone know of anything a little more flexible or single-utility? My solution gets a little nastier with bash loops to make the "..." break multilined, it's not adaptive to resizing the terminal window at all, and I'm sure there's more that I missed.



Any suggestions?










share|improve this question









New contributor




MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Closed as duplicate, but the question only shares similarities (Mine is more about a command, I learned, and not files), and the answers here didn't show up there, but if you insist

    – MadisonCooper
    yesterday







  • 2





    Fair enough. I've reopened. Note that the answer that you have accepted will only work for large outputs as noted at my answer at Command to display first few and last few lines of a file (try seq 30 | (head && tail) for instance).

    – Stéphane Chazelas
    yesterday







  • 2





    I meant that answer. That Q&A has two answers of mine because another Q&A was merged with it (see question history)

    – Stéphane Chazelas
    yesterday
















7















On queue-based clusters the Queue of pending jobs is shown from a command, say showqueue.



The command returns, in columns, a list of reasonable data like names, etc, but the columns/data don't really matter for the question.



I like using the utility watch like watch showqueue at times (with an alias of alias watch="watch " to force alias expansion of my command to watch). There is valuable data (Running jobs), in the first few lines, then pending jobs, etc, and some valuable summaries at the end.



However, at times the output of showqueue goes off the screen (Unbelievable, I know)! Ideally, I'd like some way to be able to see the beginning and end of the file at the same time.



The best I have so far is: showqueue > file; head -n 20 file > file2; echo "..." >> file2 ; tail -n 20 file >> file2; cat file2, and using watch on an alias of that.



Does anyone know of anything a little more flexible or single-utility? My solution gets a little nastier with bash loops to make the "..." break multilined, it's not adaptive to resizing the terminal window at all, and I'm sure there's more that I missed.



Any suggestions?










share|improve this question









New contributor




MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Closed as duplicate, but the question only shares similarities (Mine is more about a command, I learned, and not files), and the answers here didn't show up there, but if you insist

    – MadisonCooper
    yesterday







  • 2





    Fair enough. I've reopened. Note that the answer that you have accepted will only work for large outputs as noted at my answer at Command to display first few and last few lines of a file (try seq 30 | (head && tail) for instance).

    – Stéphane Chazelas
    yesterday







  • 2





    I meant that answer. That Q&A has two answers of mine because another Q&A was merged with it (see question history)

    – Stéphane Chazelas
    yesterday














7












7








7








On queue-based clusters the Queue of pending jobs is shown from a command, say showqueue.



The command returns, in columns, a list of reasonable data like names, etc, but the columns/data don't really matter for the question.



I like using the utility watch like watch showqueue at times (with an alias of alias watch="watch " to force alias expansion of my command to watch). There is valuable data (Running jobs), in the first few lines, then pending jobs, etc, and some valuable summaries at the end.



However, at times the output of showqueue goes off the screen (Unbelievable, I know)! Ideally, I'd like some way to be able to see the beginning and end of the file at the same time.



The best I have so far is: showqueue > file; head -n 20 file > file2; echo "..." >> file2 ; tail -n 20 file >> file2; cat file2, and using watch on an alias of that.



Does anyone know of anything a little more flexible or single-utility? My solution gets a little nastier with bash loops to make the "..." break multilined, it's not adaptive to resizing the terminal window at all, and I'm sure there's more that I missed.



Any suggestions?










share|improve this question









New contributor




MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












On queue-based clusters the Queue of pending jobs is shown from a command, say showqueue.



The command returns, in columns, a list of reasonable data like names, etc, but the columns/data don't really matter for the question.



I like using the utility watch like watch showqueue at times (with an alias of alias watch="watch " to force alias expansion of my command to watch). There is valuable data (Running jobs), in the first few lines, then pending jobs, etc, and some valuable summaries at the end.



However, at times the output of showqueue goes off the screen (Unbelievable, I know)! Ideally, I'd like some way to be able to see the beginning and end of the file at the same time.



The best I have so far is: showqueue > file; head -n 20 file > file2; echo "..." >> file2 ; tail -n 20 file >> file2; cat file2, and using watch on an alias of that.



Does anyone know of anything a little more flexible or single-utility? My solution gets a little nastier with bash loops to make the "..." break multilined, it's not adaptive to resizing the terminal window at all, and I'm sure there's more that I missed.



Any suggestions?







bash text-processing






share|improve this question









New contributor




MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited yesterday









Rui F Ribeiro

41.8k1483142




41.8k1483142






New contributor




MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









MadisonCooperMadisonCooper

413




413




New contributor




MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






MadisonCooper is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • Closed as duplicate, but the question only shares similarities (Mine is more about a command, I learned, and not files), and the answers here didn't show up there, but if you insist

    – MadisonCooper
    yesterday







  • 2





    Fair enough. I've reopened. Note that the answer that you have accepted will only work for large outputs as noted at my answer at Command to display first few and last few lines of a file (try seq 30 | (head && tail) for instance).

    – Stéphane Chazelas
    yesterday







  • 2





    I meant that answer. That Q&A has two answers of mine because another Q&A was merged with it (see question history)

    – Stéphane Chazelas
    yesterday


















  • Closed as duplicate, but the question only shares similarities (Mine is more about a command, I learned, and not files), and the answers here didn't show up there, but if you insist

    – MadisonCooper
    yesterday







  • 2





    Fair enough. I've reopened. Note that the answer that you have accepted will only work for large outputs as noted at my answer at Command to display first few and last few lines of a file (try seq 30 | (head && tail) for instance).

    – Stéphane Chazelas
    yesterday







  • 2





    I meant that answer. That Q&A has two answers of mine because another Q&A was merged with it (see question history)

    – Stéphane Chazelas
    yesterday

















Closed as duplicate, but the question only shares similarities (Mine is more about a command, I learned, and not files), and the answers here didn't show up there, but if you insist

– MadisonCooper
yesterday






Closed as duplicate, but the question only shares similarities (Mine is more about a command, I learned, and not files), and the answers here didn't show up there, but if you insist

– MadisonCooper
yesterday





2




2





Fair enough. I've reopened. Note that the answer that you have accepted will only work for large outputs as noted at my answer at Command to display first few and last few lines of a file (try seq 30 | (head && tail) for instance).

– Stéphane Chazelas
yesterday






Fair enough. I've reopened. Note that the answer that you have accepted will only work for large outputs as noted at my answer at Command to display first few and last few lines of a file (try seq 30 | (head && tail) for instance).

– Stéphane Chazelas
yesterday





2




2





I meant that answer. That Q&A has two answers of mine because another Q&A was merged with it (see question history)

– Stéphane Chazelas
yesterday






I meant that answer. That Q&A has two answers of mine because another Q&A was merged with it (see question history)

– Stéphane Chazelas
yesterday











4 Answers
4






active

oldest

votes


















13














Are you looking to do something like the following? Shows output from both head and tail.



$ showqueue | (head && tail)





share|improve this answer


















  • 5





    Some implementations of head may read more than 10 lines and leave nothing for tail to read. The utility is not supposed to do that and I believe that the GNU tools are well behave in this respect. Use head; echo '...'; tail to get the dots in there as well.

    – Kusalananda
    yesterday











  • Yeah, combined with @Kusalananda's comment it's much more succinct than my solution. I'll mark as correct for now! Thanks.

    – MadisonCooper
    yesterday






  • 4





    @Kusalananda, nope, on my system, GNU head (coreutils 8.26) reads blocks of 8192 bytes. It does try to seek back, but obviously can't in case of a pipe. Though anyway, is there really a requirement for head to not over-read? (same on Mac, it seems to read by blocks)

    – ilkkachu
    yesterday







  • 2





    @ilkkachu yeah, even as it stands the tail part is occasionally blank even on sufficiently long output (I know since I'm using head -n 35, and that's full), but fortunately it's just a convenience to watch and I can wait 3 seconds for a refresh if needed.

    – MadisonCooper
    yesterday







  • 3





    @Kusalananda, POSIX allows implementations to do that when the input is not seekable and most implementations do. Not doing it would mean reading one byte at a time which would be very inefficient (or put the data back onto the pipe where supported which would cause all sorts of different problems). The only head implementation I know that reads one byte at a time to avoid reading past the 10th newline is ksh93's head builtin.

    – Stéphane Chazelas
    yesterday


















2














awk solution for an arbitrary number of lines shown from the head and the tail (change n=3 to set the amount):



$ seq 99999 | awk -v n=3 'NR <= n; NR > n a[NR] = $0; delete a[NR-n]; 
END print "..."; for (i = NR-n+1; i <= NR; i++) if (i in a) print a[i]; '
1
2
3
...
99997
99998
99999


As it's written, the head and tail parts will not overlap, even if the input is shorter than 2*n lines.



In some awk implementations, using for (x in a) print a[x]; in the END part also works. But in general, it's not guaranteed to return the array entries in the correct order, and doesn't in e.g. mawk.






share|improve this answer

























  • If m is the number of lines in the file, and m < 2n, that will print 2n - m empty lines. Also have look here ;-). for (x in a) will iterate in order only in GNU awk; if you think that it works in mawk too, test with > 10 values.

    – mosvy
    yesterday











  • @mosvy, oh, whoops, I forgot to re-check that after realizing x in a wasn't right. Fixed now, thanks. There's also another awk answer in the question Stéphane linked to. I like the modulo trick, though!

    – ilkkachu
    yesterday



















1














Using the same approach as you, using a temporary file, but doing it slightly shorter:



showqueue >/tmp/q.out; head -n 20 /tmp/q.out; echo '...'; tail -n 20 /tmp/q.out


This would not suffer from the same issues as discussed under another answer, but would possibly show the same lines twice if the output was shorter than 40 lines.






share|improve this answer
































    0














    You can use simple awk script. Added circle buffer there n=3 is for last 3 lines



    awk 'NR<=n print $0 A[NR%n]=$0 END for (i=1; i<=n; ++i) if (NR+i>2*n)print A[(NR+i)%n] ' n=3 < <( seq 10 )


    After update its not simple anymore though,






    share|improve this answer










    New contributor




    Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.















    • 1





      This would only show the first and last line. To show more than that, you would have to change NR==1 to NR <= 10 (or something), and then collect lines into a (circular?) buffer that you later output in the END block.

      – Kusalananda
      yesterday











    • yes let me update

      – Abdurrahim
      yesterday











    • This will print some lines twice when then the number of lines is less than 2 * n.

      – mosvy
      yesterday











    • :) ok adding that as well now I am curious what you will find next :D

      – Abdurrahim
      14 hours ago










    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "106"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    MadisonCooper is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f508818%2fbash-method-for-viewing-beginning-and-end-of-file%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    13














    Are you looking to do something like the following? Shows output from both head and tail.



    $ showqueue | (head && tail)





    share|improve this answer


















    • 5





      Some implementations of head may read more than 10 lines and leave nothing for tail to read. The utility is not supposed to do that and I believe that the GNU tools are well behave in this respect. Use head; echo '...'; tail to get the dots in there as well.

      – Kusalananda
      yesterday











    • Yeah, combined with @Kusalananda's comment it's much more succinct than my solution. I'll mark as correct for now! Thanks.

      – MadisonCooper
      yesterday






    • 4





      @Kusalananda, nope, on my system, GNU head (coreutils 8.26) reads blocks of 8192 bytes. It does try to seek back, but obviously can't in case of a pipe. Though anyway, is there really a requirement for head to not over-read? (same on Mac, it seems to read by blocks)

      – ilkkachu
      yesterday







    • 2





      @ilkkachu yeah, even as it stands the tail part is occasionally blank even on sufficiently long output (I know since I'm using head -n 35, and that's full), but fortunately it's just a convenience to watch and I can wait 3 seconds for a refresh if needed.

      – MadisonCooper
      yesterday







    • 3





      @Kusalananda, POSIX allows implementations to do that when the input is not seekable and most implementations do. Not doing it would mean reading one byte at a time which would be very inefficient (or put the data back onto the pipe where supported which would cause all sorts of different problems). The only head implementation I know that reads one byte at a time to avoid reading past the 10th newline is ksh93's head builtin.

      – Stéphane Chazelas
      yesterday















    13














    Are you looking to do something like the following? Shows output from both head and tail.



    $ showqueue | (head && tail)





    share|improve this answer


















    • 5





      Some implementations of head may read more than 10 lines and leave nothing for tail to read. The utility is not supposed to do that and I believe that the GNU tools are well behave in this respect. Use head; echo '...'; tail to get the dots in there as well.

      – Kusalananda
      yesterday











    • Yeah, combined with @Kusalananda's comment it's much more succinct than my solution. I'll mark as correct for now! Thanks.

      – MadisonCooper
      yesterday






    • 4





      @Kusalananda, nope, on my system, GNU head (coreutils 8.26) reads blocks of 8192 bytes. It does try to seek back, but obviously can't in case of a pipe. Though anyway, is there really a requirement for head to not over-read? (same on Mac, it seems to read by blocks)

      – ilkkachu
      yesterday







    • 2





      @ilkkachu yeah, even as it stands the tail part is occasionally blank even on sufficiently long output (I know since I'm using head -n 35, and that's full), but fortunately it's just a convenience to watch and I can wait 3 seconds for a refresh if needed.

      – MadisonCooper
      yesterday







    • 3





      @Kusalananda, POSIX allows implementations to do that when the input is not seekable and most implementations do. Not doing it would mean reading one byte at a time which would be very inefficient (or put the data back onto the pipe where supported which would cause all sorts of different problems). The only head implementation I know that reads one byte at a time to avoid reading past the 10th newline is ksh93's head builtin.

      – Stéphane Chazelas
      yesterday













    13












    13








    13







    Are you looking to do something like the following? Shows output from both head and tail.



    $ showqueue | (head && tail)





    share|improve this answer













    Are you looking to do something like the following? Shows output from both head and tail.



    $ showqueue | (head && tail)






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered yesterday









    Timothy PulliamTimothy Pulliam

    1,3851025




    1,3851025







    • 5





      Some implementations of head may read more than 10 lines and leave nothing for tail to read. The utility is not supposed to do that and I believe that the GNU tools are well behave in this respect. Use head; echo '...'; tail to get the dots in there as well.

      – Kusalananda
      yesterday











    • Yeah, combined with @Kusalananda's comment it's much more succinct than my solution. I'll mark as correct for now! Thanks.

      – MadisonCooper
      yesterday






    • 4





      @Kusalananda, nope, on my system, GNU head (coreutils 8.26) reads blocks of 8192 bytes. It does try to seek back, but obviously can't in case of a pipe. Though anyway, is there really a requirement for head to not over-read? (same on Mac, it seems to read by blocks)

      – ilkkachu
      yesterday







    • 2





      @ilkkachu yeah, even as it stands the tail part is occasionally blank even on sufficiently long output (I know since I'm using head -n 35, and that's full), but fortunately it's just a convenience to watch and I can wait 3 seconds for a refresh if needed.

      – MadisonCooper
      yesterday







    • 3





      @Kusalananda, POSIX allows implementations to do that when the input is not seekable and most implementations do. Not doing it would mean reading one byte at a time which would be very inefficient (or put the data back onto the pipe where supported which would cause all sorts of different problems). The only head implementation I know that reads one byte at a time to avoid reading past the 10th newline is ksh93's head builtin.

      – Stéphane Chazelas
      yesterday












    • 5





      Some implementations of head may read more than 10 lines and leave nothing for tail to read. The utility is not supposed to do that and I believe that the GNU tools are well behave in this respect. Use head; echo '...'; tail to get the dots in there as well.

      – Kusalananda
      yesterday











    • Yeah, combined with @Kusalananda's comment it's much more succinct than my solution. I'll mark as correct for now! Thanks.

      – MadisonCooper
      yesterday






    • 4





      @Kusalananda, nope, on my system, GNU head (coreutils 8.26) reads blocks of 8192 bytes. It does try to seek back, but obviously can't in case of a pipe. Though anyway, is there really a requirement for head to not over-read? (same on Mac, it seems to read by blocks)

      – ilkkachu
      yesterday







    • 2





      @ilkkachu yeah, even as it stands the tail part is occasionally blank even on sufficiently long output (I know since I'm using head -n 35, and that's full), but fortunately it's just a convenience to watch and I can wait 3 seconds for a refresh if needed.

      – MadisonCooper
      yesterday







    • 3





      @Kusalananda, POSIX allows implementations to do that when the input is not seekable and most implementations do. Not doing it would mean reading one byte at a time which would be very inefficient (or put the data back onto the pipe where supported which would cause all sorts of different problems). The only head implementation I know that reads one byte at a time to avoid reading past the 10th newline is ksh93's head builtin.

      – Stéphane Chazelas
      yesterday







    5




    5





    Some implementations of head may read more than 10 lines and leave nothing for tail to read. The utility is not supposed to do that and I believe that the GNU tools are well behave in this respect. Use head; echo '...'; tail to get the dots in there as well.

    – Kusalananda
    yesterday





    Some implementations of head may read more than 10 lines and leave nothing for tail to read. The utility is not supposed to do that and I believe that the GNU tools are well behave in this respect. Use head; echo '...'; tail to get the dots in there as well.

    – Kusalananda
    yesterday













    Yeah, combined with @Kusalananda's comment it's much more succinct than my solution. I'll mark as correct for now! Thanks.

    – MadisonCooper
    yesterday





    Yeah, combined with @Kusalananda's comment it's much more succinct than my solution. I'll mark as correct for now! Thanks.

    – MadisonCooper
    yesterday




    4




    4





    @Kusalananda, nope, on my system, GNU head (coreutils 8.26) reads blocks of 8192 bytes. It does try to seek back, but obviously can't in case of a pipe. Though anyway, is there really a requirement for head to not over-read? (same on Mac, it seems to read by blocks)

    – ilkkachu
    yesterday






    @Kusalananda, nope, on my system, GNU head (coreutils 8.26) reads blocks of 8192 bytes. It does try to seek back, but obviously can't in case of a pipe. Though anyway, is there really a requirement for head to not over-read? (same on Mac, it seems to read by blocks)

    – ilkkachu
    yesterday





    2




    2





    @ilkkachu yeah, even as it stands the tail part is occasionally blank even on sufficiently long output (I know since I'm using head -n 35, and that's full), but fortunately it's just a convenience to watch and I can wait 3 seconds for a refresh if needed.

    – MadisonCooper
    yesterday






    @ilkkachu yeah, even as it stands the tail part is occasionally blank even on sufficiently long output (I know since I'm using head -n 35, and that's full), but fortunately it's just a convenience to watch and I can wait 3 seconds for a refresh if needed.

    – MadisonCooper
    yesterday





    3




    3





    @Kusalananda, POSIX allows implementations to do that when the input is not seekable and most implementations do. Not doing it would mean reading one byte at a time which would be very inefficient (or put the data back onto the pipe where supported which would cause all sorts of different problems). The only head implementation I know that reads one byte at a time to avoid reading past the 10th newline is ksh93's head builtin.

    – Stéphane Chazelas
    yesterday





    @Kusalananda, POSIX allows implementations to do that when the input is not seekable and most implementations do. Not doing it would mean reading one byte at a time which would be very inefficient (or put the data back onto the pipe where supported which would cause all sorts of different problems). The only head implementation I know that reads one byte at a time to avoid reading past the 10th newline is ksh93's head builtin.

    – Stéphane Chazelas
    yesterday













    2














    awk solution for an arbitrary number of lines shown from the head and the tail (change n=3 to set the amount):



    $ seq 99999 | awk -v n=3 'NR <= n; NR > n a[NR] = $0; delete a[NR-n]; 
    END print "..."; for (i = NR-n+1; i <= NR; i++) if (i in a) print a[i]; '
    1
    2
    3
    ...
    99997
    99998
    99999


    As it's written, the head and tail parts will not overlap, even if the input is shorter than 2*n lines.



    In some awk implementations, using for (x in a) print a[x]; in the END part also works. But in general, it's not guaranteed to return the array entries in the correct order, and doesn't in e.g. mawk.






    share|improve this answer

























    • If m is the number of lines in the file, and m < 2n, that will print 2n - m empty lines. Also have look here ;-). for (x in a) will iterate in order only in GNU awk; if you think that it works in mawk too, test with > 10 values.

      – mosvy
      yesterday











    • @mosvy, oh, whoops, I forgot to re-check that after realizing x in a wasn't right. Fixed now, thanks. There's also another awk answer in the question Stéphane linked to. I like the modulo trick, though!

      – ilkkachu
      yesterday
















    2














    awk solution for an arbitrary number of lines shown from the head and the tail (change n=3 to set the amount):



    $ seq 99999 | awk -v n=3 'NR <= n; NR > n a[NR] = $0; delete a[NR-n]; 
    END print "..."; for (i = NR-n+1; i <= NR; i++) if (i in a) print a[i]; '
    1
    2
    3
    ...
    99997
    99998
    99999


    As it's written, the head and tail parts will not overlap, even if the input is shorter than 2*n lines.



    In some awk implementations, using for (x in a) print a[x]; in the END part also works. But in general, it's not guaranteed to return the array entries in the correct order, and doesn't in e.g. mawk.






    share|improve this answer

























    • If m is the number of lines in the file, and m < 2n, that will print 2n - m empty lines. Also have look here ;-). for (x in a) will iterate in order only in GNU awk; if you think that it works in mawk too, test with > 10 values.

      – mosvy
      yesterday











    • @mosvy, oh, whoops, I forgot to re-check that after realizing x in a wasn't right. Fixed now, thanks. There's also another awk answer in the question Stéphane linked to. I like the modulo trick, though!

      – ilkkachu
      yesterday














    2












    2








    2







    awk solution for an arbitrary number of lines shown from the head and the tail (change n=3 to set the amount):



    $ seq 99999 | awk -v n=3 'NR <= n; NR > n a[NR] = $0; delete a[NR-n]; 
    END print "..."; for (i = NR-n+1; i <= NR; i++) if (i in a) print a[i]; '
    1
    2
    3
    ...
    99997
    99998
    99999


    As it's written, the head and tail parts will not overlap, even if the input is shorter than 2*n lines.



    In some awk implementations, using for (x in a) print a[x]; in the END part also works. But in general, it's not guaranteed to return the array entries in the correct order, and doesn't in e.g. mawk.






    share|improve this answer















    awk solution for an arbitrary number of lines shown from the head and the tail (change n=3 to set the amount):



    $ seq 99999 | awk -v n=3 'NR <= n; NR > n a[NR] = $0; delete a[NR-n]; 
    END print "..."; for (i = NR-n+1; i <= NR; i++) if (i in a) print a[i]; '
    1
    2
    3
    ...
    99997
    99998
    99999


    As it's written, the head and tail parts will not overlap, even if the input is shorter than 2*n lines.



    In some awk implementations, using for (x in a) print a[x]; in the END part also works. But in general, it's not guaranteed to return the array entries in the correct order, and doesn't in e.g. mawk.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    ilkkachuilkkachu

    62.7k10103180




    62.7k10103180












    • If m is the number of lines in the file, and m < 2n, that will print 2n - m empty lines. Also have look here ;-). for (x in a) will iterate in order only in GNU awk; if you think that it works in mawk too, test with > 10 values.

      – mosvy
      yesterday











    • @mosvy, oh, whoops, I forgot to re-check that after realizing x in a wasn't right. Fixed now, thanks. There's also another awk answer in the question Stéphane linked to. I like the modulo trick, though!

      – ilkkachu
      yesterday


















    • If m is the number of lines in the file, and m < 2n, that will print 2n - m empty lines. Also have look here ;-). for (x in a) will iterate in order only in GNU awk; if you think that it works in mawk too, test with > 10 values.

      – mosvy
      yesterday











    • @mosvy, oh, whoops, I forgot to re-check that after realizing x in a wasn't right. Fixed now, thanks. There's also another awk answer in the question Stéphane linked to. I like the modulo trick, though!

      – ilkkachu
      yesterday

















    If m is the number of lines in the file, and m < 2n, that will print 2n - m empty lines. Also have look here ;-). for (x in a) will iterate in order only in GNU awk; if you think that it works in mawk too, test with > 10 values.

    – mosvy
    yesterday





    If m is the number of lines in the file, and m < 2n, that will print 2n - m empty lines. Also have look here ;-). for (x in a) will iterate in order only in GNU awk; if you think that it works in mawk too, test with > 10 values.

    – mosvy
    yesterday













    @mosvy, oh, whoops, I forgot to re-check that after realizing x in a wasn't right. Fixed now, thanks. There's also another awk answer in the question Stéphane linked to. I like the modulo trick, though!

    – ilkkachu
    yesterday






    @mosvy, oh, whoops, I forgot to re-check that after realizing x in a wasn't right. Fixed now, thanks. There's also another awk answer in the question Stéphane linked to. I like the modulo trick, though!

    – ilkkachu
    yesterday












    1














    Using the same approach as you, using a temporary file, but doing it slightly shorter:



    showqueue >/tmp/q.out; head -n 20 /tmp/q.out; echo '...'; tail -n 20 /tmp/q.out


    This would not suffer from the same issues as discussed under another answer, but would possibly show the same lines twice if the output was shorter than 40 lines.






    share|improve this answer





























      1














      Using the same approach as you, using a temporary file, but doing it slightly shorter:



      showqueue >/tmp/q.out; head -n 20 /tmp/q.out; echo '...'; tail -n 20 /tmp/q.out


      This would not suffer from the same issues as discussed under another answer, but would possibly show the same lines twice if the output was shorter than 40 lines.






      share|improve this answer



























        1












        1








        1







        Using the same approach as you, using a temporary file, but doing it slightly shorter:



        showqueue >/tmp/q.out; head -n 20 /tmp/q.out; echo '...'; tail -n 20 /tmp/q.out


        This would not suffer from the same issues as discussed under another answer, but would possibly show the same lines twice if the output was shorter than 40 lines.






        share|improve this answer















        Using the same approach as you, using a temporary file, but doing it slightly shorter:



        showqueue >/tmp/q.out; head -n 20 /tmp/q.out; echo '...'; tail -n 20 /tmp/q.out


        This would not suffer from the same issues as discussed under another answer, but would possibly show the same lines twice if the output was shorter than 40 lines.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited yesterday

























        answered yesterday









        KusalanandaKusalananda

        138k17258426




        138k17258426





















            0














            You can use simple awk script. Added circle buffer there n=3 is for last 3 lines



            awk 'NR<=n print $0 A[NR%n]=$0 END for (i=1; i<=n; ++i) if (NR+i>2*n)print A[(NR+i)%n] ' n=3 < <( seq 10 )


            After update its not simple anymore though,






            share|improve this answer










            New contributor




            Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.















            • 1





              This would only show the first and last line. To show more than that, you would have to change NR==1 to NR <= 10 (or something), and then collect lines into a (circular?) buffer that you later output in the END block.

              – Kusalananda
              yesterday











            • yes let me update

              – Abdurrahim
              yesterday











            • This will print some lines twice when then the number of lines is less than 2 * n.

              – mosvy
              yesterday











            • :) ok adding that as well now I am curious what you will find next :D

              – Abdurrahim
              14 hours ago















            0














            You can use simple awk script. Added circle buffer there n=3 is for last 3 lines



            awk 'NR<=n print $0 A[NR%n]=$0 END for (i=1; i<=n; ++i) if (NR+i>2*n)print A[(NR+i)%n] ' n=3 < <( seq 10 )


            After update its not simple anymore though,






            share|improve this answer










            New contributor




            Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.















            • 1





              This would only show the first and last line. To show more than that, you would have to change NR==1 to NR <= 10 (or something), and then collect lines into a (circular?) buffer that you later output in the END block.

              – Kusalananda
              yesterday











            • yes let me update

              – Abdurrahim
              yesterday











            • This will print some lines twice when then the number of lines is less than 2 * n.

              – mosvy
              yesterday











            • :) ok adding that as well now I am curious what you will find next :D

              – Abdurrahim
              14 hours ago













            0












            0








            0







            You can use simple awk script. Added circle buffer there n=3 is for last 3 lines



            awk 'NR<=n print $0 A[NR%n]=$0 END for (i=1; i<=n; ++i) if (NR+i>2*n)print A[(NR+i)%n] ' n=3 < <( seq 10 )


            After update its not simple anymore though,






            share|improve this answer










            New contributor




            Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.










            You can use simple awk script. Added circle buffer there n=3 is for last 3 lines



            awk 'NR<=n print $0 A[NR%n]=$0 END for (i=1; i<=n; ++i) if (NR+i>2*n)print A[(NR+i)%n] ' n=3 < <( seq 10 )


            After update its not simple anymore though,







            share|improve this answer










            New contributor




            Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            share|improve this answer



            share|improve this answer








            edited 14 hours ago





















            New contributor




            Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            answered yesterday









            AbdurrahimAbdurrahim

            1012




            1012




            New contributor




            Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.





            New contributor





            Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            Abdurrahim is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.







            • 1





              This would only show the first and last line. To show more than that, you would have to change NR==1 to NR <= 10 (or something), and then collect lines into a (circular?) buffer that you later output in the END block.

              – Kusalananda
              yesterday











            • yes let me update

              – Abdurrahim
              yesterday











            • This will print some lines twice when then the number of lines is less than 2 * n.

              – mosvy
              yesterday











            • :) ok adding that as well now I am curious what you will find next :D

              – Abdurrahim
              14 hours ago












            • 1





              This would only show the first and last line. To show more than that, you would have to change NR==1 to NR <= 10 (or something), and then collect lines into a (circular?) buffer that you later output in the END block.

              – Kusalananda
              yesterday











            • yes let me update

              – Abdurrahim
              yesterday











            • This will print some lines twice when then the number of lines is less than 2 * n.

              – mosvy
              yesterday











            • :) ok adding that as well now I am curious what you will find next :D

              – Abdurrahim
              14 hours ago







            1




            1





            This would only show the first and last line. To show more than that, you would have to change NR==1 to NR <= 10 (or something), and then collect lines into a (circular?) buffer that you later output in the END block.

            – Kusalananda
            yesterday





            This would only show the first and last line. To show more than that, you would have to change NR==1 to NR <= 10 (or something), and then collect lines into a (circular?) buffer that you later output in the END block.

            – Kusalananda
            yesterday













            yes let me update

            – Abdurrahim
            yesterday





            yes let me update

            – Abdurrahim
            yesterday













            This will print some lines twice when then the number of lines is less than 2 * n.

            – mosvy
            yesterday





            This will print some lines twice when then the number of lines is less than 2 * n.

            – mosvy
            yesterday













            :) ok adding that as well now I am curious what you will find next :D

            – Abdurrahim
            14 hours ago





            :) ok adding that as well now I am curious what you will find next :D

            – Abdurrahim
            14 hours ago










            MadisonCooper is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            MadisonCooper is a new contributor. Be nice, and check out our Code of Conduct.












            MadisonCooper is a new contributor. Be nice, and check out our Code of Conduct.











            MadisonCooper is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f508818%2fbash-method-for-viewing-beginning-and-end-of-file%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Triangular numbers and gcdProving sum of a set is $0 pmod n$ if $n$ is odd, or $fracn2 pmod n$ if $n$ is even?Is greatest common divisor of two numbers really their smallest linear combination?GCD, LCM RelationshipProve a set of nonnegative integers with greatest common divisor 1 and closed under addition has all but finite many nonnegative integers.all pairs of a and b in an equation containing gcdTriangular Numbers Modulo $k$ - Hit All Values?Understanding the Existence and Uniqueness of the GCDGCD and LCM with logical symbolsThe greatest common divisor of two positive integers less than 100 is equal to 3. Their least common multiple is twelve times one of the integers.Suppose that for all integers $x$, $x|a$ and $x|b$ if and only if $x|c$. Then $c = gcd(a,b)$Which is the gcd of 2 numbers which are multiplied and the result is 600000?

            Србија Садржај Етимологија Географија Историја Политички систем и уставно-правно уређење Становништво Привреда Образовање Култура Спорт Државни празници Галерија Напомене Референце Литература Спољашње везе Мени за навигацију44°48′N 20°28′E / 44.800° СГШ; 20.467° ИГД / 44.800; 20.46744°48′N 20°28′E / 44.800° СГШ; 20.467° ИГД / 44.800; 20.467ууРезултати пописа 2011. према старости и полуу„Положај, рељеф и клима”„Europe: Serbia”„Основни подаци”„Gross domestic product based on purchasing-power-parity (PPP) valuation of country GDP”„Human Development Report 2018 – "Human Development Indices and Indicators 6”„Устав Републике Србије”Правопис српскога језикаGoogle DriveComparative Hungarian Cultural StudiesCalcium and Magnesium in Groundwater: Occurrence and Significance for Human Health„UNSD — Methodology”„Процене становништва | Републички завод за статистику Србије”The Age of Nepotism: Travel Journals and Observations from the Balkans During the Depression„The Serbian Revolution and the Serbian State”„Устав Србије”„Serbia a few steps away from concluding WTO accession negotiations”„A credible enlargement perspective for and enhanced EU engagement with the Western Balkans”„Freedom in the World 2017”„Serbia: On the Way to EU Accession”„Human Development Indices and Indicators: 2018 Statistical Update”„2018 Social Progress Index”„Global Peace Index”Sabres of Two Easts: An Untold History of Muslims in Eastern Europe, Their Friends and Foes„Пројекат Растко—Лузица”„Serbia: Introduction”„Serbia”оригинала„The World Factbook: Serbia”„The World Factbook: Kosovo”„Border Police Department”„Uredba o kontroli prelaska administrativne linije prema Autonomnoj pokrajini Kosovo i Metohija”оригиналаIvana Carevic, Velimir Jovanovic, STRATIGRAPHIC-STRUCTURAL CHARACTERISTICS OF MAČVA BASIN, UDC 911.2:551.7(497.11), pp. 1Archived„About the Carpathians – Carpathian Heritage Society”оригинала„O Srbiji”оригинала„Статистички годишњак Србије, 2009: Географски прегледГеографија за осми разред основне школе„Отворена, електронска база едукационих радова”„Влада Републике Србије: Положај, рељеф и клима”„Копрен (Стара планина)”„Туристичка дестинација-Србија”„Висина водопада”„РХМЗ — Републички Хидрометеоролошки завод Србије Кнеза Вишеслава 66 Београд”„Фауна Србије”„Српске шуме на издисају”„Lepih šest odsto Srbije”„Илустрована историја Срба — Увод”„Винчанска култура - Градска општина Гроцка”„''„Винча — Праисторијска метропола”''”оригиналаЈужни Словени под византијском влашћу (600—1025)Држава маћедонских Словена„Карађорђе истина и мит, Проф. др Радош Љушић, Вечерње новости, фељтон, 18 наставака, 24. август - 10. септембар 2003.”„Политика: Како је утврђена војна неутралност, 13. јануар. 2010, приступљено децембра 2012.”„Србија и РС оживеле Дејтонски споразум”„Са српским пасошем у 104 земље”Војска Србије | О Војсци | Војска Србије — Улога, намена и задациАрхивираноВојска Србије | ОрганизацијаАрхивираноОдлука о изради Стратегије просторног развоја Републике Србије до 2020. годинеЗакон о територијалној организацији Републике СрбијеЗакон о државној управиНајчешће постављана питања.„Смањење броја статистичких региона кроз измене Закона о регионалном развоју”„2011 Human development Report”„Službena upotreba jezika i pisama”„Попис становништва, домаћинстава и станова 2011. године у Републици Србији. Књига 4: Вероисповест, матерњи језик и национална припадност”„Вероисповест, матерњи језик и национална”„Специјална известитељка УН за слободу религије и вероисповести Асма Јахангир, код Заштитника грађана Саше Јанковића”„Закон о државним и другим празницима у Републици Србији”„Веронаука у српским школама”„Serbia – Ancestral Genography Atlas”Бела књига Милошевићеве владавинеоригиналаGross domestic product based on purchasing-power-parity (PPP) per capita GDP БДП 2007—2013Актуелни показатељи — Република Србија„Попис становништва, домаћинстава и станова 2011. године у Републици Србији Књига 7: Економска активност”Zemlje kandidati za članstvo u EU„Putin drops South Stream gas pipeline to EU, courts Turkey”„„Соко — историјат””оригинала„„Рембас — историјат””оригинала„„Лубница — историјат””оригинала„„Штаваљ — Историјат””оригинала„„Боговина — историјат””оригинала„„Јасеновац — историјат””оригинала„„Вршка чука — историјат””оригинала„„Ибарски рудници — историјат””оригинала„Закон о просторном плану Републике Србије од 2010 до 2020”„Кривични законик — Недозвољена изградња нуклеарних постројења, члан 267”„Б92: Srbija uklonila obogaćeni uranijum, 25. октобар 2011”„Коришћење енергије ветра у Србији — природни услови и практична примена”„Енергија ветра”„Србија може да прави струју од сунца, биомасе, воде и ветра”„Моја електрана и друге ветрењаче”„Биомаса, струја без инвестиција”„Auto-karte Srbije”„www.srbija.gov.rs Статистике о Србији”оригинала„Статистика зе месец децембар и 2016. годину”„Turizam u Srbiji”„Univerzitet u Beogradu: Vek i po akademskog znanja”„Vojnomedicinska akademija: 165 godina tradicije i napretka”Никола Гиљен, Соња Јовићевић Јов и Јелена Мандић: Мирослављево јеванђеље; Текст је публикован у ревији „Историја” и настао је као део научно-истраживачког рада Фонда „Принцеза Оливера”„World music асоцијација Србије”оригинала„World music у Србији”оригинала„Pogledajte: Boban Marković svira u redakciji „Blica”!”„Eurovision Song Contest 2007 Final”„Projekat Rastko, Alojz Ujes: Joakim Vujic”„Унеско”„Списак локалитета Светске баштине”„Guča i Egzit zaludeli svet”оригинала„Sabor trubača GUČA”„Interesting facts about Exit”оригинала„FIFA Association Information”„Serbia women win EuroBasket title, gain first Olympics berth”„Odbojkašice ispisale istoriju – Srbija je svetski prvak!”„Сајт Ватерполо савеза Србије, Освојене медаље”„Сајт ФК Црвена звезда, Бари”„Сајт ФК Црвена звезда, Токио”„Blic:Zlatna Milica! Mandićeva donela Srbiji najsjajnije odličje u Londonu!”„Милица Мандић освојила златну медаљу („Политика”, 12. август 2012)”„Златни Давор Штефанек”„DŽUDO ŠAMPIONAT Majdov osvojio svetsko zlato”„Španovićeva trećim skokom svih vremena do zlata!”„Чудо Иване Шпановић — 7,24 м („Политика”, 5. март 2017)”The Age of Nepotism: Travel Journals and Observations from the Balkans During the DepressionCalcium and Magnesium in Groundwater: Occurrence and Significance for Human HealthComparative Hungarian Cultural StudiesБела књига Милошевићеве владавинеоригиналаComparative Hungarian Cultural StudiesSabres of Two Easts: An Untold History of Muslims in Eastern Europe, Their Friends and FoesГеографија за осми разред основне школеSerbia: the country, people, life, customsМедијиВодичПодациВлада Републике СрбијеНародна скупштина Републике СрбијеНародна канцеларија председника Републике СрбијеНародна банка СрбијеТуристичка организација СрбијеПортал еУправе Републике СрбијеРепубличко јавно правобранилаштвоууууууWorldCat151202876n851959190000 0000 9526 67094054598-24101000570825ge130919

            Barbados Ynhâld Skiednis | Geografy | Demografy | Navigaasjemenu